org.springframework.security.oauth2.jwt.JwtException Java Examples
The following examples show how to use
org.springframework.security.oauth2.jwt.JwtException.
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: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void invalidSubject() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .audience("123456") .expirationTime(Date.from(Instant.now().plusSeconds(36000))) .issuer("https://securetoken.google.com/123456") .issueTime(Date.from(Instant.now().minusSeconds(3600))) .claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond()) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456")); validators.add(new FirebaseTokenValidator("123456")); DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators); RestOperations operations = mockRestOperations(); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt: sub claim can not be empty"); }
Example #2
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void invalidIssuedAt() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .audience("123456") .expirationTime(Date.from(Instant.now().plusSeconds(36000))) .issuer("https://securetoken.google.com/123456") .issueTime(Date.from(Instant.now().plusSeconds(3600))) .claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond()) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456")); validators.add(new FirebaseTokenValidator("123456")); DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators); RestOperations operations = mockRestOperations(); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt: iat claim header must be in the past"); }
Example #3
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void invalidAudienceTests() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .audience("123") .expirationTime(Date.from(Instant.now().plusSeconds(36000))) .issuer("https://securetoken.google.com/123456") .issueTime(Date.from(Instant.now().minusSeconds(3600))) .claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond()) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456")); validators.add(new FirebaseTokenValidator("123456")); DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators); RestOperations operations = mockRestOperations(); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt: This aud claim is not equal to the configured audience"); }
Example #4
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void invalidIssuerTests() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .audience("123456") .expirationTime(Date.from(Instant.now().plusSeconds(36000))) .issuer("https://spring.local/123456") .issueTime(Date.from(Instant.now().minusSeconds(3600))) .claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond()) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456")); DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators); RestOperations operations = mockRestOperations(); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt"); }
Example #5
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void expiredTokenTests() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .expirationTime(Date.from(Instant.now().minusSeconds(3600))) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators); RestOperations operations = mockRestOperations(); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt: Jwt expired at"); }
Example #6
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void connectionErrorTests() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class); when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success()); RestOperations operations = mock(RestOperations.class); when(operations.exchange(eq("https://spring.local"), eq(HttpMethod.GET), isNull(), eq(new ParameterizedTypeReference<Map<String, String>>() { }))).thenThrow(new RestClientException("Could not connect to remote peer")); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("Error fetching public keys"); }
Example #7
Source File: FirebaseJwtTokenDecoder.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Override public Jwt decode(String token) throws JwtException { SignedJWT jwt = parse(token); if (isExpired()) { try { keysLock.tryLock(); refresh(); } finally { keysLock.unlock(); } } JwtDecoder decoder = delegates.get(jwt.getHeader().getKeyID()); if (decoder == null) { throw new JwtException("No certificate found for key: " + jwt.getHeader().getKeyID()); } return decoder.decode(token); }
Example #8
Source File: FirebaseJwtTokenDecoder.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
private SignedJWT parse(String token) { try { JWT jwt = JWTParser.parse(token); if (!(jwt instanceof SignedJWT)) { throw new JwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm()); } return (SignedJWT) jwt; } catch (Exception ex) { throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex); } }
Example #9
Source File: OidcUserManagementAutoConfiguration.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
Set<GrantedAuthority> extract(final ClientRegistration clientRegistration, final String tokenValue) { try { // Token is already verified by spring security final JwtDecoder jwtDecoder = new NimbusJwtDecoderJwkSupport( clientRegistration.getProviderDetails().getJwkSetUri()); final Jwt token = jwtDecoder.decode(tokenValue); return extract(clientRegistration.getClientId(), token.getClaims()); } catch (final JwtException e) { throw new OAuth2AuthenticationException(INVALID_REQUEST, e); } }
Example #10
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void keyNotFoundTests() throws Exception { JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("two").build(); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet); OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class); when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success()); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mockRestOperations(), "https://spring.local", validator); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(signedJWT.serialize())) .withMessageStartingWith("No certificate found for key: "); }
Example #11
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void unsignedTokenTests() { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); PlainJWT plainJWT = new PlainJWT(claimsSet); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mock(RestOperations.class), "https://spring.local", mock(OAuth2TokenValidator.class)); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(plainJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt"); }
Example #12
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void postValidationActionIsNotExecutedIfFail() { String jwt = new JwtGenerator(clientId, "subdomain").deriveAudiences(true) .setJwtHeaderKeyId("legacy-token-key").setJku(null).getToken().getTokenValue(); try { jwtDecoderWithPostAction.decode(jwt); Assert.fail(); } catch (JwtException e) { Assert.assertFalse(postActionExecuted); } }
Example #13
Source File: FirebaseJwtTokenDecoder.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
private void refresh() { if (!isExpired()) { return; } try { ResponseEntity<Map<String, String>> response = restClient.exchange(googlePublicKeysEndpoint, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() { }); Long expiresAt = parseCacheControlHeaders(response.getHeaders()); this.expires = expiresAt > -1L ? (System.currentTimeMillis() + expiresAt * 1000) : 0L; if (!response.getStatusCode().is2xxSuccessful()) { throw new JwtException("Error retrieving public certificates from remote endpoint"); } delegates.clear(); for (String key : response.getBody().keySet()) { try { NimbusJwtDecoder nimbusJwtDecoder = NimbusJwtDecoder.withPublicKey((RSAPublicKey) convertToX509Cert(response.getBody().get(key)).getPublicKey()) .signatureAlgorithm(SignatureAlgorithm.from("RS256")) .build(); nimbusJwtDecoder.setJwtValidator(tokenValidator); delegates.put(key, nimbusJwtDecoder); } catch (Exception ce) { logger.error("Could not read certificate for key {}", key); } } } catch (Exception e) { throw new JwtException("Error fetching public keys", e); } }
Example #14
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_whenJwksContainsFragment_throwsException() throws IOException { String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8); XsuaaJwtDecoder cut = (XsuaaJwtDecoder)new XsuaaJwtDecoderBuilder(configuration).build(); cut.setTokenInfoExtractor(new TokenInfoExtractorImpl("https://subdomain.myauth.ondemand.com/token_keys#token_keys")); assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class) .hasMessageContaining("Jwt token does not contain a valid 'jku' header parameter:"); }
Example #15
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_whenJwksContainQueryParameters_throwsException() throws IOException { String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8); XsuaaJwtDecoder cut = (XsuaaJwtDecoder)new XsuaaJwtDecoderBuilder(configuration).build(); cut.setTokenInfoExtractor(new TokenInfoExtractorImpl("https://subdomain.myauth.ondemand.com/token_keys?a=b")); assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class) .hasMessageContaining("Jwt token does not contain a valid 'jku' header parameter: "); }
Example #16
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_whenJwksContainsInvalidPath_throwsException() throws IOException { String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8); XsuaaJwtDecoder cut = (XsuaaJwtDecoder)new XsuaaJwtDecoderBuilder(configuration).build(); cut.setTokenInfoExtractor(new TokenInfoExtractorImpl("https://subdomain.myauth.ondemand.com/wrong_endpoint")); assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class) .hasMessageContaining("Jwt token does not contain a valid 'jku' header parameter"); }
Example #17
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_whenJwksContainsInvalidJwksDomain_throwsException() throws IOException { String token = IOUtils.resourceToString("/token_user.txt", StandardCharsets.UTF_8); XsuaaJwtDecoder cut = (XsuaaJwtDecoder)new XsuaaJwtDecoderBuilder(configuration).build(); cut.setTokenInfoExtractor(new TokenInfoExtractorImpl("https://subdomain.wrongoauth.ondemand.com/token_keys")); assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class) .hasMessageContaining("JWT verification failed: Do not trust 'jku' token header"); }
Example #18
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_withNonMatchingVerificationKey_throwsException() throws IOException { String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8); final JwtDecoder cut = new XsuaaJwtDecoderBuilder(configuration).build(); assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class) .hasMessageContaining("Cannot verify with online token key, jku, kid, uaadomain is null"); }
Example #19
Source File: SpringSecurityContextTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test(expected = IllegalArgumentException.class) // Passed JwtDecoder instance must be of type 'XsuaaJwtDecoder' public void initSecurityContextRaiseExceptionIfNotXsuaaJwtDecoder() { String message = ""; SpringSecurityContext.init(token_1.getTokenValue(), new JwtDecoder() { @Override public Jwt decode(String s) throws JwtException { return token_1; } }, new DefaultAuthoritiesExtractor()); }
Example #20
Source File: ReactiveXsuaaJwtDecoder.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Override public Mono<Jwt> decode(String token) throws JwtException { return Mono.just(token).map(jwtToken -> { try { return JWTParser.parse(jwtToken); } catch (ParseException e) { throw new JwtException("Error initializing JWT decoder:" + e.getMessage()); } }).map(jwtToken -> { String cacheKey = tokenInfoExtractor.getJku(jwtToken) + tokenInfoExtractor.getKid(jwtToken); return cache.get(cacheKey, k -> this.getDecoder(tokenInfoExtractor.getJku(jwtToken))); }).flatMap(decoder -> decoder.decode(token)) .doOnSuccess(jwt -> postValidationActions.forEach(act -> act.perform(jwt))); }