com.auth0.jwt.algorithms.Algorithm Java Examples
The following examples show how to use
com.auth0.jwt.algorithms.Algorithm.
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: ConstantTokenProviderTest.java From dcos-commons with Apache License 2.0 | 6 votes |
private String createToken() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); Algorithm algorithm = Algorithm.RSA256(( RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate()); return JWT.create() .withExpiresAt(Date.from(Instant.now().plusSeconds(120))) .withClaim("uid", "test") .sign(algorithm); }
Example #2
Source File: JwtAuthenticationProviderTest.java From auth0-spring-security-api with MIT License | 6 votes |
@Test public void shouldFailToAuthenticateUsingJWKIfAudienceClaimDoesNotMatch() throws Exception { Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenReturn(jwk); when(jwk.getPublicKey()).thenReturn(keyPair.getPublic()); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("some-audience") .withIssuer("test-issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(BadCredentialsException.class); exception.expectMessage("Not a valid token"); exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class)); provider.authenticate(authentication); }
Example #3
Source File: JWTVerifierTest.java From java-jwt with MIT License | 6 votes |
@Test public void shouldRemoveAudienceWhenPassingNull() throws Exception { Algorithm algorithm = mock(Algorithm.class); JWTVerifier verifier = JWTVerifier.init(algorithm) .withAudience("John") .withAudience((String) null) .build(); assertThat(verifier.claims, is(notNullValue())); assertThat(verifier.claims, not(hasKey("aud"))); verifier = JWTVerifier.init(algorithm) .withAudience("John") .withAudience((String[]) null) .build(); assertThat(verifier.claims, is(notNullValue())); assertThat(verifier.claims, not(hasKey("aud"))); }
Example #4
Source File: JwtManager.java From Mars-Java with MIT License | 6 votes |
/** * WT生成Token. * @param obj * @return str */ public String createToken(Object obj) { Date iatDate = new Date(); // expire time Calendar nowTime = Calendar.getInstance(); nowTime.add(calendarField, calendarInterval); Date expiresDate = nowTime.getTime(); // header Map Map<String, Object> map = new HashMap<>(); map.put("alg", "HS256"); map.put("typ", "JWT"); JWTCreator.Builder builder = JWT.create().withHeader(map); JSONObject json = JSONObject.parseObject(JSON.toJSONString(obj)); for (String key : json.keySet()) { builder.withClaim(key, json.get(key).toString()); } builder.withIssuedAt(iatDate); // sign time builder.withExpiresAt(expiresDate); // expire time String token = builder.sign(Algorithm.HMAC256(SECRET)); // signature return token; }
Example #5
Source File: JWTVerifierFactory.java From spring-jwt-gateway with Apache License 2.0 | 6 votes |
@Bean @Qualifier("jwk") public JWTVerifier create(@Value("${jwt.issuer}") String issuer, @Value("${jwt.audience}") String audience) throws JwkException, IOException { UrlJwkProvider urlJwkProvider = new UrlJwkProvider(issuer); RestTemplate restTemplate = new RestTemplate(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(restTemplate.getForObject(issuer + "/.well-known/jwks.json", String.class)); String kid = jsonNode.get("keys").get(0).get("kid").asText(); Jwk jwk = urlJwkProvider.get(kid); return JWT.require(Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null)) .withIssuer(issuer) .withAudience(audience) .build(); }
Example #6
Source File: JwtAuthenticationProviderTest.java From auth0-spring-security-api with MIT License | 6 votes |
@Test public void shouldAuthenticateUsingJWK() throws Exception { Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenReturn(jwk); when(jwk.getPublicKey()).thenReturn(keyPair.getPublic()); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("test-audience") .withIssuer("test-issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); Authentication result = provider.authenticate(authentication); assertThat(result, is(notNullValue())); assertThat(result, is(not(equalTo(authentication)))); }
Example #7
Source File: JwtAuthenticationProviderTest.java From auth0-spring-security-api with MIT License | 6 votes |
@SuppressWarnings("unchecked") @Test public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception { JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("test-audience") .withIssuer("test-issuer") .withHeader(keyIdHeader) .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(AuthenticationServiceException.class); exception.expectMessage("Could not retrieve jwks from issuer"); exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class)); provider.authenticate(authentication); }
Example #8
Source File: JWTCreatorTest.java From java-jwt with MIT License | 6 votes |
@Test public void shouldAddAudience() throws Exception { String signed = JWTCreator.init() .withAudience("Mark") .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJhdWQiOiJNYXJrIn0")); String signedArr = JWTCreator.init() .withAudience("Mark", "David") .sign(Algorithm.HMAC256("secret")); assertThat(signedArr, is(notNullValue())); assertThat(TokenUtils.splitToken(signedArr)[1], is("eyJhdWQiOlsiTWFyayIsIkRhdmlkIl19")); }
Example #9
Source File: IdTokenVerifierTest.java From auth0-java with MIT License | 6 votes |
@Test public void succeedsWithValidTokenUsingDefaultClockAndHttpDomain() { String token = JWT.create() .withSubject("auth0|sdk458fks") .withAudience(AUDIENCE) .withIssuedAt(getYesterday()) .withExpiresAt(getTomorrow()) .withIssuer("http://" + DOMAIN + "/") .withClaim("nonce", "nonce") .sign(Algorithm.HMAC256("secret")); DecodedJWT decodedJWT = JWT.decode(token); SignatureVerifier verifier = mock(SignatureVerifier.class); when(verifier.verifySignature(token)).thenReturn(decodedJWT); IdTokenVerifier.init("http://" + DOMAIN + "/", AUDIENCE, verifier) .build() .verify(token, "nonce"); }
Example #10
Source File: OAuth2AuthenticationResourceTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerificationException { Token responseToken = response.readEntity(Token.class); assertEquals("BEARER", responseToken.getTokenType().name()); String token = responseToken.getToken(); Algorithm algorithm = Algorithm.HMAC256("myJWT4Gr4v1t33_S3cr3t"); JWTVerifier jwtVerifier = JWT.require(algorithm).build(); DecodedJWT jwt = jwtVerifier.verify(token); assertEquals(jwt.getSubject(),"[email protected]"); assertEquals("Jane", jwt.getClaim("firstname").asString()); assertEquals("gravitee-management-auth", jwt.getClaim("iss").asString()); assertEquals("[email protected]", jwt.getClaim("sub").asString()); assertEquals("[email protected]", jwt.getClaim("email").asString()); assertEquals("Doe", jwt.getClaim("lastname").asString()); }
Example #11
Source File: JwtAuthenticationProviderTest.java From auth0-spring-security-api with MIT License | 6 votes |
@Test public void shouldFailToAuthenticateUsingJWKIfMissingIssuerClaim() throws Exception { Jwk jwk = mock(Jwk.class); JwkProvider jwkProvider = mock(JwkProvider.class); KeyPair keyPair = RSAKeyPair(); when(jwkProvider.get(eq("key-id"))).thenReturn(jwk); when(jwk.getPublicKey()).thenReturn(keyPair.getPublic()); JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience"); Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id"); String token = JWT.create() .withAudience("test-audience") .withHeader(keyIdHeader) .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate())); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); exception.expect(BadCredentialsException.class); exception.expectMessage("Not a valid token"); exception.expectCause(Matchers.<Throwable>instanceOf(InvalidClaimException.class)); provider.authenticate(authentication); }
Example #12
Source File: JWTCreatorTest.java From java-jwt with MIT License | 6 votes |
@Test @SuppressWarnings("unchecked") public void shouldAcceptCustomClaimWithNullListAndRemoveClaim() throws Exception { String jwt = JWTCreator.init() .withClaim("list", "stubValue") .withClaim("list", (List<String>) null) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); String body = new String(Base64.decodeBase64(parts[1]), StandardCharsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = (Map<String, Object>) mapper.readValue(body, Map.class); assertThat(map, anEmptyMap()); }
Example #13
Source File: JWTCreatorTest.java From java-jwt with MIT License | 6 votes |
@Test public void shouldNotOverwriteKeyIdIfAddedFromECDSAAlgorithms() throws Exception { ECPrivateKey privateKey = (ECPrivateKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_EC_256, "EC"); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); when(provider.getPrivateKeyId()).thenReturn("my-key-id"); when(provider.getPrivateKey()).thenReturn(privateKey); String signed = JWTCreator.init() .withKeyId("real-key-id") .sign(Algorithm.ECDSA256(provider)); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); assertThat(headerJson, JsonMatcher.hasEntry("kid", "my-key-id")); }
Example #14
Source File: Tools.java From flowchat with GNU General Public License v3.0 | 5 votes |
public static final Algorithm getJWTAlgorithm() { Algorithm JWTAlgorithm = null; try { JWTAlgorithm = Algorithm.HMAC256(DataSources.PROPERTIES.getProperty("jdbc.password")); } catch (UnsupportedEncodingException | JWTCreationException exception) { } return JWTAlgorithm; }
Example #15
Source File: JWTTest.java From java-jwt with MIT License | 5 votes |
@Test public void shouldCreateAnEmptyRSA384SignedToken() throws Exception { String signed = JWT.create().sign(Algorithm.RSA384((RSAKey) PemUtils.readPrivateKeyFromFile(PRIVATE_KEY_FILE_RSA, "RSA"))); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); assertThat(headerJson, JsonMatcher.hasEntry("alg", "RS384")); assertThat(headerJson, JsonMatcher.hasEntry("typ", "JWT")); assertThat(parts[1], is("e30")); JWTVerifier verified = JWT.require(Algorithm.RSA384((RSAKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_RSA, "RSA"))) .build(); assertThat(verified, is(notNullValue())); }
Example #16
Source File: JWTTest.java From java-jwt with MIT License | 5 votes |
@Test public void shouldCreateAnEmptyHMAC512SignedToken() throws Exception { String signed = JWT.create().sign(Algorithm.HMAC512("secret")); assertThat(signed, is(notNullValue())); String[] parts = signed.split("\\."); String headerJson = new String(Base64.decodeBase64(parts[0]), StandardCharsets.UTF_8); assertThat(headerJson, JsonMatcher.hasEntry("alg", "HS512")); assertThat(headerJson, JsonMatcher.hasEntry("typ", "JWT")); assertThat(parts[1], is("e30")); JWTVerifier verified = JWT.require(Algorithm.HMAC512("secret")) .build(); assertThat(verified, is(notNullValue())); }
Example #17
Source File: BearerSecurityContextRepositoryTest.java From auth0-spring-security-api with MIT License | 5 votes |
@Test public void shouldLoadContextWithAuthentication() throws Exception { String token = JWT.create() .sign(Algorithm.HMAC256("secret")); BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); when(request.getHeader("Authorization")).thenReturn("Bearer " + token); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(notNullValue())); assertThat(context.getAuthentication(), is(instanceOf(PreAuthenticatedAuthenticationJsonWebToken.class))); assertThat(context.getAuthentication().isAuthenticated(), is(false)); }
Example #18
Source File: JwtHelper.java From litemall with MIT License | 5 votes |
public Integer verifyTokenAndGetUserId(String token) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET); JWTVerifier verifier = JWT.require(algorithm) .withIssuer(ISSUSER) .build(); DecodedJWT jwt = verifier.verify(token); Map<String, Claim> claims = jwt.getClaims(); Claim claim = claims.get("userId"); return claim.asInt(); } catch (JWTVerificationException exception){ // exception.printStackTrace(); } return 0; }
Example #19
Source File: JwtHelper.java From flow-platform-x with Apache License 2.0 | 5 votes |
public static boolean verify(String token, User user, boolean checkExpire) { try { Algorithm algorithm = Algorithm.HMAC256(user.getPasswordOnMd5()); JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build(); verifier.verify(token); return true; } catch (JWTVerificationException e) { if (e instanceof TokenExpiredException) { return !checkExpire; } return false; } }
Example #20
Source File: JWTTest.java From java-jwt with MIT License | 5 votes |
@Test public void shouldGetAlgorithm() throws Exception { String token = "eyJhbGciOiJIUzI1NiJ9.e30.XmNK3GpH3Ys_7wsYBfq4C3M6goz71I7dTgUkuIa5lyQ"; DecodedJWT jwt = JWT.require(Algorithm.HMAC256("secret")) .build() .verify(token); assertThat(jwt, is(notNullValue())); assertThat(jwt.getAlgorithm(), is("HS256")); }
Example #21
Source File: AuthSign.java From charging_pile_cloud with MIT License | 5 votes |
/** * 过期时间使用redis 的过期时间 * @param id 用户id * @param object 用户信息 * @return */ public static String tokenSign(Long id, JSONObject object) throws UnsupportedEncodingException { //私钥及加密算法 Algorithm algorithm=Algorithm.HMAC256(SECRET); return JWT.create().withHeader(jwtHeader) .withClaim(ID,id) .withClaim(OBJECT,object.toJSONString()) .withClaim(DATE,System.currentTimeMillis()) .sign(algorithm); }
Example #22
Source File: TokenAuthenticationFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
public TokenAuthenticationFilter(final String jwtSecret, final CookieGenerator cookieGenerator, final UserService userService, final TokenService tokenService) { Algorithm algorithm = Algorithm.HMAC256(jwtSecret); jwtVerifier = JWT.require(algorithm).build(); this.cookieGenerator = cookieGenerator; this.userService = userService; this.tokenService = tokenService; }
Example #23
Source File: JwtUtil.java From jeecg-boot-with-activiti with MIT License | 5 votes |
/** * 生成签名,5min后过期 * * @param username 用户名 * @param secret 用户的密码 * @return 加密的token */ public static String sign(String username, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm); }
Example #24
Source File: JWTVerifierTest.java From java-jwt with MIT License | 5 votes |
@Test(expected = InvalidClaimException.class) public void shouldThrowOnFutureIssuedAt() throws Exception { Clock clock = mock(Clock.class); when(clock.getToday()).thenReturn(new Date(DATE_TOKEN_MS_VALUE - 1000)); String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0Nzc1OTJ9.CWq-6pUXl1bFg81vqOUZbZrheO2kUBd2Xr3FUZmvudE"; JWTVerifier.BaseVerification verification = (JWTVerifier.BaseVerification) JWTVerifier.init(Algorithm.HMAC256("secret")); DecodedJWT jwt = verification.build(clock).verify(token); assertThat(jwt, is(notNullValue())); }
Example #25
Source File: JWTTest.java From java-jwt with MIT License | 5 votes |
@Test public void shouldAcceptECDSA384Algorithm() throws Exception { String token = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJhdXRoMCJ9.50UU5VKNdF1wfykY8jQBKpvuHZoe6IZBJm5NvoB8bR-hnRg6ti-CHbmvoRtlLfnHfwITa_8cJMy6TenMC2g63GQHytc8rYoXqbwtS4R0Ko_AXbLFUmfxnGnMC6v4MS_z"; ECKey key = (ECKey) PemUtils.readPublicKeyFromFile(PUBLIC_KEY_FILE_EC_384, "EC"); DecodedJWT jwt = JWT.require(Algorithm.ECDSA384(key)) .build() .verify(token); assertThat(jwt, is(notNullValue())); }
Example #26
Source File: JWTCreatorTest.java From java-jwt with MIT License | 5 votes |
@Test public void shouldAcceptCustomArrayClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() .withArrayClaim("name", new Long[]{1L, 2L, 3L}) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjpbMSwyLDNdfQ")); }
Example #27
Source File: JwtUtil.java From jeecg-cloud with Apache License 2.0 | 5 votes |
/** * 校验token是否正确 * * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */ public static boolean verify(String token, String username, String secret) { try { // 根据密码生成JWT效验器 Algorithm algorithm = Algorithm.HMAC256(SecureUtil.md5(secret)); JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build(); // 效验TOKEN DecodedJWT jwt = verifier.verify(token); return true; } catch (Exception exception) { return false; } }
Example #28
Source File: JWTTokenManager.java From data-transfer-project with Apache License 2.0 | 5 votes |
/** Create the {@link Algorithm} to be used for signing and parsing tokens. */ private static Algorithm createAlgorithm(String secret) { try { return Algorithm.HMAC256(secret); } catch (IllegalArgumentException e) { throw new RuntimeException(e); // TODO: Better error handling } }
Example #29
Source File: JwtUtil.java From demo-project with MIT License | 5 votes |
/** * Description: 解密jwt * * @param token token * @param secret secret * @return java.util.Map<java.lang.String , com.auth0.jwt.interfaces.Claim> * @author fanxb * @date 2019/3/4 18:14 */ public static Map<String, Claim> decode(String token, String secret) { if (token == null || token.length() == 0) { throw new CustomException("token为空:" + token); } Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier jwtVerifier = JWT.require(algorithm).build(); DecodedJWT decodedJWT = jwtVerifier.verify(token); return decodedJWT.getClaims(); }
Example #30
Source File: JWTCreatorTest.java From java-jwt with MIT License | 5 votes |
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void shouldRefuseCustomMapClaimForNonStringKey() throws Exception { Map data = new HashMap<>(); data.put(new Object(), "value"); exception.expect(IllegalArgumentException.class); JWTCreator.init() .withClaim("pojo", (Map<String, Object>) data) .sign(Algorithm.HMAC256("secret")); }