io.jsonwebtoken.SignatureAlgorithm Java Examples
The following examples show how to use
io.jsonwebtoken.SignatureAlgorithm.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestJwtAuth.java From jobson with Apache License 2.0 | 6 votes |
@Test public void testClientCanAuthenticateWithAJwt() { final JsonWebTokenConfig jwtConfigInFixture = (JsonWebTokenConfig)RULE.getConfiguration().getAuthenticationConfiguration(); final String secretKeyBase64 = jwtConfigInFixture.getSecretKey(); final byte[] secretKeyData = Base64.getDecoder().decode(secretKeyBase64); final SignatureAlgorithm alg = jwtConfigInFixture.getSignatureAlgorithm(); final Key secretKey = new SecretKeySpec(secretKeyData, 0, secretKeyData.length, alg.toString()); final String username = TestHelpers.generateRandomString(); final Principal userPrincipal = new PrincipalImpl(username); final String jwt = JsonWebTokenAuthenticator.createJwtToken(alg, secretKey, userPrincipal); final Invocation.Builder b = generateRequest(RULE, HTTP_USERS_PATH + "/current"); b.header("Authorization", "Bearer " + jwt); final Response response = b.get(); assertThat(response.getStatus()).isEqualTo(OK); final APIUserDetails parsedResponse = response.readEntity(APIUserDetails.class); assertThat(parsedResponse.getId().toString()).isEqualTo(username); }
Example #2
Source File: JsonWebTokenService.java From spring-boot-mongodb-jwt with Apache License 2.0 | 6 votes |
@Override public String getToken(final String username, final String password) { if (username == null || password == null) { return null; } final User user = (User) userDetailsService.loadUserByUsername(username); Map<String, Object> tokenData = new HashMap<>(); if (password.equals(user.getPassword())) { tokenData.put("clientType", "user"); tokenData.put("userID", user.getId()); tokenData.put("username", user.getUsername()); tokenData.put("token_create_date", LocalDateTime.now()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, tokenExpirationTime); tokenData.put("token_expiration_date", calendar.getTime()); JwtBuilder jwtBuilder = Jwts.builder(); jwtBuilder.setExpiration(calendar.getTime()); jwtBuilder.setClaims(tokenData); return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact(); } else { throw new ServiceException("Authentication error", this.getClass().getName()); } }
Example #3
Source File: AccountController.java From bootshiro with MIT License | 6 votes |
/** * description 登录签发 JWT ,这里已经在 passwordFilter 进行了登录认证 * * @param request 1 * @param response 2 * @return com.usthe.bootshiro.domain.vo.Message */ @ApiOperation(value = "用户登录", notes = "POST用户登录签发JWT") @PostMapping("/login") public Message accountLogin(HttpServletRequest request, HttpServletResponse response) { Map<String, String> params = RequestResponseUtil.getRequestBodyMap(request); String appId = params.get("appId"); // 根据appId获取其对应所拥有的角色(这里设计为角色对应资源,没有权限对应资源) String roles = accountService.loadAccountRole(appId); // 时间以秒计算,token有效刷新时间是token有效过期时间的2倍 long refreshPeriodTime = 36000L; String jwt = JsonWebTokenUtil.issueJWT(UUID.randomUUID().toString(), appId, "token-server", refreshPeriodTime >> 1, roles, null, SignatureAlgorithm.HS512); // 将签发的JWT存储到Redis: {JWT-SESSION-{appID} , jwt} redisTemplate.opsForValue().set("JWT-SESSION-" + appId, jwt, refreshPeriodTime, TimeUnit.SECONDS); AuthUser authUser = userService.getUserByAppId(appId); authUser.setPassword(null); authUser.setSalt(null); LogExeManager.getInstance().executeLogTask(LogTaskFactory.loginLog(appId, IpUtil.getIpFromRequest(WebUtils.toHttp(request)), (short) 1, "登录成功")); return new Message().ok(1003, "issue jwt success").addData("jwt", jwt).addData("user", authUser); }
Example #4
Source File: AuthorizationController.java From spring-mvc-react with MIT License | 6 votes |
@JsonView(Views.Public.class) @RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseEntity<?> login(@RequestBody LoginModel data) { User user = userService.getByUsername(data.getUsername()); if (user == null) { return new ResponseEntity(new LoginResponseBody(false, null, "User with that name isn't exist"), HttpStatus.OK); } if (!Objects.equals(user.getPassword(), MD5.getHash(data.getPassword()))) { return new ResponseEntity(new LoginResponseBody(false, null, "wrong_password"), HttpStatus.OK); } String token = Jwts.builder() .setSubject(data.getUsername()) .signWith(SignatureAlgorithm.HS512, key) .compact(); return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK); }
Example #5
Source File: JwtTokenIssuer.java From jersey-jwt-springsecurity with MIT License | 6 votes |
/** * Issue a JWT token * * @param authenticationTokenDetails * @return */ public String issueToken(AuthenticationTokenDetails authenticationTokenDetails) { return Jwts.builder() .setId(authenticationTokenDetails.getId()) .setIssuer(settings.getIssuer()) .setAudience(settings.getAudience()) .setSubject(authenticationTokenDetails.getUsername()) .setIssuedAt(Date.from(authenticationTokenDetails.getIssuedDate().toInstant())) .setExpiration(Date.from(authenticationTokenDetails.getExpirationDate().toInstant())) .claim(settings.getAuthoritiesClaimName(), authenticationTokenDetails.getAuthorities()) .claim(settings.getRefreshCountClaimName(), authenticationTokenDetails.getRefreshCount()) .claim(settings.getRefreshLimitClaimName(), authenticationTokenDetails.getRefreshLimit()) .signWith(SignatureAlgorithm.HS256, settings.getSecret()) .compact(); }
Example #6
Source File: ApiTestUtils.java From stitch-android-sdk with Apache License 2.0 | 6 votes |
/** * Gets an refresh token JWT for testing that is always the same. */ public static String getTestRefreshToken() { if (TEST_REFRESH_TOKEN != null) { return TEST_REFRESH_TOKEN; } final Map<String, Object> claims = new HashMap<>(); claims.put("typ", "refresh"); return Jwts.builder() .setClaims(claims) .setIssuedAt(Date.from(Instant.now().minus(Duration.ofHours(1)))) .setSubject("uniqueUserID") .setExpiration(new Date(((Calendar.getInstance().getTimeInMillis() + (5 * 60 * 1000))))) .setClaims(claims) .signWith( SignatureAlgorithm.HS256, "abcdefghijklmnopqrstuvwxyz1234567890".getBytes(StandardCharsets.UTF_8)) .compact(); }
Example #7
Source File: JwtUtil.java From xmanager with Apache License 2.0 | 6 votes |
/** * 创建jwt * @param id * @param subject * @param ttlMillis * @return * @throws Exception */ public String createJWT(String id, String subject, long ttlMillis) throws Exception { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, key); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); }
Example #8
Source File: HTTPJwtAuthenticatorTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@Test public void testNonStringAlternativeSubject() throws Exception { Settings settings = Settings.builder() .put("signing_key", BaseEncoding.base64().encode(secretKey)) .put("subject_key", "asub") .build(); String jwsToken = Jwts.builder() .setSubject("Leonard McCoy") .claim("roles", "role1,role2") .claim("asub", false) .signWith(SignatureAlgorithm.HS512, secretKey).compact(); HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", jwsToken); AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null); Assert.assertNotNull(creds); Assert.assertEquals("false", creds.getUsername()); Assert.assertEquals(0, creds.getBackendRoles().size()); }
Example #9
Source File: JsonWebTokenAuthenticatorTest.java From jobson with Apache License 2.0 | 6 votes |
/** * Test that .authenticate does not throw an error when provided with * a valid JWT token. */ @Test public void testAuthenticateDoesNotThrowWHenProvidedWithAValidJWTToken() throws AuthenticationException { final Key secretKey = createSecretKey(); final SignatureAlgorithm signatureAlgorithm = getValidSignatureAlgorithm(); final Principal principal = generatePrincipal(); final String jwt = createJwtToken(signatureAlgorithm, secretKey, principal); final JsonWebTokenAuthenticator authenticator = createAuthenticator(secretKey, signatureAlgorithm); // Shouldn't throw, because we created a valid jwt token // using the same secret key as the authenticator. authenticator.authenticate(jwt); }
Example #10
Source File: JwtHelper.java From kisso with Apache License 2.0 | 6 votes |
/** * <p> * 验证签名并解析 * </p> */ public static JwtParser verifyParser() { try { SSOConfig config = SSOConfig.getInstance(); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm()); if (SSOConstants.RSA.equals(signatureAlgorithm.getFamilyName())) { if(null == RSA_PUBLICKEY) { ClassPathResource resource = new ClassPathResource(config.getRsaCertStore()); RSA_PUBLICKEY = RsaKeyHelper.getRsaPublicKey(resource.getInputStream()); } // RSA 签名验证 return Jwts.parserBuilder().setSigningKey(RSA_PUBLICKEY).build(); } // 普通签名验证 SecretKey secretKey = getSecretKey(config.getSignKey(), signatureAlgorithm); return Jwts.parserBuilder().setSigningKey(secretKey).build(); } catch (Exception e) { throw new KissoException("verifyParser error.", e); } }
Example #11
Source File: HTTPJwtAuthenticatorTest.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@Test public void testNullClaim() throws Exception { Settings settings = Settings.builder() .put("signing_key", BaseEncoding.base64().encode(secretKey)) .put("roles_key", "roles") .build(); String jwsToken = Jwts.builder() .setSubject("Leonard McCoy") .claim("roles", null) .signWith(SignatureAlgorithm.HS512, secretKey).compact(); HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null); Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", jwsToken); AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null); Assert.assertNotNull(creds); Assert.assertEquals("Leonard McCoy", creds.getUsername()); Assert.assertEquals(0, creds.getBackendRoles().size()); }
Example #12
Source File: DefaultSignatureValidatorFactory.java From jjwt with Apache License 2.0 | 6 votes |
@Override public SignatureValidator createSignatureValidator(SignatureAlgorithm alg, Key key) { Assert.notNull(alg, "SignatureAlgorithm cannot be null."); Assert.notNull(key, "Signing Key cannot be null."); switch (alg) { case HS256: case HS384: case HS512: return new MacValidator(alg, key); case RS256: case RS384: case RS512: case PS256: case PS384: case PS512: return new RsaSignatureValidator(alg, key); case ES256: case ES384: case ES512: return new EllipticCurveSignatureValidator(alg, key); default: throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing."); } }
Example #13
Source File: JwtUtil.java From light-reading-cloud with MIT License | 6 votes |
/** * 构建JWT对象 * @param expire * @param user * @return */ public static String buildJwt(Date expire, UserVO user) { String jwt = Jwts.builder() // 使用HS256加密算法 .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 过期时间 .setExpiration(expire) .claim("loginName",user.getLoginName()) .claim("nickName",user.getNickName()) .claim("phoneNumber",user.getPhoneNumber()) .claim("headImgUrl",user.getHeadImgUrl()) .claim("uuid",user.getUuid()) .claim("id",user.getId()) .compact(); return jwt; }
Example #14
Source File: OpenIdSigningKeyResolver.java From line-sdk-android with Apache License 2.0 | 6 votes |
private Key resolveSigningKey(final JwsHeader header) { final LineApiResponse<JWKSet> response = apiClient.getJWKSet(); if (!response.isSuccess()) { Log.e(TAG, "failed to get LINE JSON Web Key Set [JWK] document."); return null; } final JWKSet jwkSet = response.getResponseData(); final String keyId = header.getKeyId(); final JWK jwk = jwkSet.getJWK(keyId); if (jwk == null) { Log.e(TAG, "failed to find Key by Id: " + keyId); return null; } final String algorithm = header.getAlgorithm(); final SignatureAlgorithm alg = SignatureAlgorithm.forName(algorithm); if (alg.isEllipticCurve()) { return generateECPublicKey(jwk); } throw new SecurityException("Unsupported signature algorithm '" + algorithm + '\''); }
Example #15
Source File: HttpExample.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** Create an ES-based JWT for the given project id, signed with the given private key. */ private static String createJwtEs(String projectId, String privateKeyFile) throws Exception { DateTime now = new DateTime(); // Create a JWT to authenticate this device. The device will be disconnected after the token // expires, and will have to reconnect with a new token. The audience field should always be set // to the GCP project id. JwtBuilder jwtBuilder = Jwts.builder() .setIssuedAt(now.toDate()) .setExpiration(now.plusMinutes(20).toDate()) .setAudience(projectId); byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("EC"); return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact(); }
Example #16
Source File: SSOClientTest.java From sso-client with Apache License 2.0 | 6 votes |
@Before public void before(){ String pk = org.apache.commons.codec.binary.Base64.encodeBase64String(keyPair.getPublic().getEncoded()); stubFor(get("/oauth2/publickey").willReturn(aResponse().withStatus(200).withBody(pk))); JwtBuilder builder = jwtBuilder(System.currentTimeMillis()+3600*1000L) .signWith(SignatureAlgorithm.RS256,keyPair.getPrivate()); jwtToken = builder.compact(); SSOConfig config = new SSOConfig().autoConfigureUrls(baseUrl); config.setClientId("test"); config.setClientSecret("test_secret"); config.setResourceName("resourceName"); config.setRedirectUri("http://www.example.com"); client = new SSOClient(config); basicHeader = SSOUtils.encodeBasicAuthorizationHeader(config.getClientId(),config.getClientSecret()); }
Example #17
Source File: OAuthFilterTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testFilterNotSecureSecCtx() { final Key key = secretKeyFor(SignatureAlgorithm.HS512); final String token = Jwts.builder().setSubject(WEBID1).signWith(key).compact(); final ContainerRequestContext mockCtx = mock(ContainerRequestContext.class); when(mockCtx.getSecurityContext()).thenReturn(mockSecurityContext); when(mockSecurityContext.isSecure()).thenReturn(true); when(mockCtx.getHeaderString(AUTHORIZATION)).thenReturn("Bearer " + token); final OAuthFilter filter = new OAuthFilter(); filter.setAuthenticator(new JwtAuthenticator(key)); filter.filter(mockCtx); verify(mockCtx).setSecurityContext(securityArgument.capture()); assertEquals(WEBID1, securityArgument.getValue().getUserPrincipal().getName(), "Unexpected agent IRI!"); assertEquals(OAuthFilter.SCHEME, securityArgument.getValue().getAuthenticationScheme(), "Unexpected scheme!"); assertTrue(securityArgument.getValue().isSecure(), "Unexpected secure flag!"); assertFalse(securityArgument.getValue().isUserInRole("some role"), "Unexpectedly in user role!"); }
Example #18
Source File: ServerPrivateKeyTest.java From athenz with Apache License 2.0 | 5 votes |
@Test public void testServerPrivateKeyEC() { final File rsaPrivateKey = new File("./src/test/resources/unit_test_ec_private.key"); PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey); ServerPrivateKey key = new ServerPrivateKey(privateKey, "zms.2"); assertEquals(key.getKey(), privateKey); assertEquals(key.getId(), "zms.2"); assertEquals(key.getAlgorithm(), SignatureAlgorithm.ES256); }
Example #19
Source File: JwtUtils.java From sdb-mall with Apache License 2.0 | 5 votes |
/** * 生成jwt token */ public String generateToken(String userId) { Date nowDate = new Date(); //过期时间 Date expireDate = new Date(nowDate.getTime() + expire * 1000); return Jwts.builder() .setHeaderParam("typ", "JWT") .setSubject(userId+"") .setIssuedAt(nowDate) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
Example #20
Source File: JwtTokenUtil.java From HIS with Apache License 2.0 | 5 votes |
/** * 根据负责生成JWT的token */ private String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
Example #21
Source File: EllipticCurveProvider.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Returns the expected signature byte array length (R + S parts) for * the specified ECDSA algorithm. * * @param alg The ECDSA algorithm. Must be supported and not * {@code null}. * * @return The expected byte array length for the signature. * * @throws JwtException If the algorithm is not supported. */ public static int getSignatureByteArrayLength(final SignatureAlgorithm alg) throws JwtException { switch (alg) { case ES256: return 64; case ES384: return 96; case ES512: return 132; default: throw new JwtException("Unsupported Algorithm: " + alg.name()); } }
Example #22
Source File: JwtTokenUtils.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
public static String createToken(String username, String role, boolean isRememberMe) { long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION; HashMap<String, Object> map = new HashMap<>(); map.put(ROLE_CLAIMS, role); return Jwts.builder() .signWith(SignatureAlgorithm.HS512, SECRET) .setClaims(map) .setIssuer(ISS) .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) .compact(); }
Example #23
Source File: JwtSubjectCreatorTest.java From sureness with Apache License 2.0 | 5 votes |
@Test public void createSubject() { String jwt = JsonWebTokenUtil.issueJwt(UUID.randomUUID().toString(), "tom", "token-server", 36000L, Arrays.asList("role2", "rol3"), null, Boolean.FALSE, SignatureAlgorithm.HS512); HttpServletRequest request = createNiceMock(HttpServletRequest.class); expect(request.getHeader(AUTHORIZATION)).andReturn(BEARER + " " + jwt); expect(request.getRequestURI()).andReturn("/api/v1/book"); expect(request.getMethod()).andReturn("put"); expect(request.getRemoteHost()).andReturn("192.167.2.1"); replay(request); assertNotNull(creator.createSubject(request)); verify(request); }
Example #24
Source File: _JwtTokenUtil.java From generator-spring-rest-jwt with MIT License | 5 votes |
String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
Example #25
Source File: JwtUtils.java From withme3.0 with MIT License | 5 votes |
public static String createJWT(String authUser) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); JwtBuilder builder = Jwts.builder() .setHeaderParam("typ", "jwt") .setHeaderParam("alg", "HS256") .setPayload(authUser) .signWith(signatureAlgorithm, signingKey); return builder.compact(); }
Example #26
Source File: JwtTokenUtils.java From framework with Apache License 2.0 | 5 votes |
/** * 生成token * * @param claim claim * @return token */ public static String createToken(Map<String, Object> claim) { LocalDateTime expireLocalDateTime = LocalDateTime.now().plus(adamProperties.getSecurity().getSignIn().getExpiration(), ChronoUnit.SECONDS); String jwtPrefix = adamProperties.getSecurity().getJwtToken().getPrefix(); String jwtToken = Jwts.builder() .setClaims(claim) .setExpiration(DateUtils.localDateTimeToDate(expireLocalDateTime)) .signWith(SignatureAlgorithm.HS512, adamProperties.getSecurity().getJwtToken().getSecret()) .compact(); return jwtPrefix + " " + jwtToken; }
Example #27
Source File: JwtTokenUtil.java From docker-crash-course with MIT License | 5 votes |
private String doGenerateToken(Map<String, Object> claims, String subject) { final Date createdDate = clock.now(); final Date expirationDate = calculateExpirationDate(createdDate); return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(createdDate) .setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact(); }
Example #28
Source File: JwtTokenUtil.java From mall-learning with Apache License 2.0 | 5 votes |
/** * 根据负责生成JWT的token */ private String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
Example #29
Source File: ChaincodeController.java From balance-transfer-java with Apache License 2.0 | 5 votes |
/** * Return the status as the particular user is enrolled * * @param Status * of the user registered and enrolled in blockchain. * @return the status as string */ @RequestMapping(value = "/enroll", method = RequestMethod.POST) public ResponseEntity<String> enroll(@RequestBody UserDto user) { String result = chaincodeService.enrollAndRegister(user.getUsername()); if (result != "Failed to enroll user") { String jwtToken = ""; if (user.getUsername() == null) { return ResponseEntity .status(HttpStatus.FORBIDDEN) .body("please enter username in request body"); } String username = user.getUsername(); jwtToken = Jwts.builder().setSubject(username).claim("roles", "user").setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, "secretkey").setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)).compact(); return ResponseEntity .status(HttpStatus.OK) .body(result + " jwt:" + jwtToken); } return ResponseEntity .status(HttpStatus.FORBIDDEN) .body("Something went wrong"); }
Example #30
Source File: JsonWebTokenUtilTest.java From sureness with Apache License 2.0 | 5 votes |
@Test public void isNotJsonWebToken() { String jwt = JsonWebTokenUtil.issueJwt(UUID.randomUUID().toString(), "tom", "token-server", 36000L, Arrays.asList("role2", "rol3"), null, Boolean.FALSE, SignatureAlgorithm.HS512); boolean flag = JsonWebTokenUtil.isNotJsonWebToken(jwt); assertFalse(flag); flag = JsonWebTokenUtil.isNotJsonWebToken("gsgdsghdbhegxhsgdjsdj"); assertTrue(flag); }