org.springframework.security.oauth2.jwt.Jwt Java Examples
The following examples show how to use
org.springframework.security.oauth2.jwt.Jwt.
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 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 #2
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 #3
Source File: ReactiveXsuaaJwtDecoder.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
ReactiveXsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration, int cacheValidityInSeconds, int cacheSize, OAuth2TokenValidator<Jwt> tokenValidators, Collection<PostValidationAction> postValidationActions) { cache = Caffeine.newBuilder().expireAfterWrite(cacheValidityInSeconds, TimeUnit.SECONDS).maximumSize(cacheSize) .build(); this.tokenInfoExtractor = new TokenInfoExtractor() { @Override public String getJku(JWT jwt) { return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_JKU, null); } @Override public String getKid(JWT jwt) { return (String) jwt.getHeader().toJSONObject().getOrDefault(CLAIM_KID, null); } @Override public String getUaaDomain(JWT jwt) { return xsuaaServiceConfiguration.getUaaDomain(); } }; this.tokenValidators.addAll(Arrays.asList(tokenValidators)); this.postValidationActions = postValidationActions != null ? postValidationActions : Collections.EMPTY_LIST; }
Example #4
Source File: XsuaaAudienceValidator.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
@Override public OAuth2TokenValidatorResult validate(Jwt token) { String tokenClientId = token.getClaimAsString(TokenClaims.CLAIM_CLIENT_ID); if (StringUtils.isEmpty(tokenClientId)) { return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, "Jwt token must contain 'cid' (client_id)", null)); } List<String> allowedAudiences = getAllowedAudiences(token); for (Map.Entry<String, String> xsuaaConfig : appIdClientIdMap.entrySet()) { if (checkMatch(xsuaaConfig.getKey(), xsuaaConfig.getValue(), tokenClientId, allowedAudiences)) { return OAuth2TokenValidatorResult.success(); } } String description = String.format("Jwt token with allowed audiences %s matches none of these: %s", allowedAudiences, appIdClientIdMap.keySet().toString()); return OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, description, null)); }
Example #5
Source File: TokenAuthenticationConverterTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 6 votes |
@Test public void authoritiesHaveLocalScopesWithoutAppIdPrefix() { String scopeWithNamespace = xsAppName + ".iot.Delete"; String scopeWithOtherAppId = "anyAppId!t200." + xsAppName + ".Delete"; Jwt jwt = new JwtGenerator() .addScopes(xsAppName + "." + scopeAdmin, scopeRead, scopeWithNamespace, scopeWithOtherAppId) .getToken(); AbstractAuthenticationToken authenticationToken = tokenConverterLocalScopesOnly.convert(jwt); assertThat(authenticationToken.getAuthorities().size(), is(3)); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("iot.Delete"))); assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("Read"))); }
Example #6
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 #7
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void validTokenTests() 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().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); Jwt jwt = decoder.decode(signedJWT.serialize()); assertThat(jwt.getClaims()).isNotEmpty(); }
Example #8
Source File: IapAuthenticationAutoConfiguration.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Bean @ConditionalOnMissingBean(name = "iapJwtDelegatingValidator") public DelegatingOAuth2TokenValidator<Jwt> iapJwtDelegatingValidator(IapAuthenticationProperties properties, AudienceValidator audienceValidator) { List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>(); validators.add(new JwtTimestampValidator()); validators.add(new JwtIssuerValidator(properties.getIssuer())); validators.add(audienceValidator); if (LOGGER.isInfoEnabled()) { LOGGER.info("Audience configured for IAP JWT validation: " + audienceValidator.getAudience()); } return new DelegatingOAuth2TokenValidator<>(validators); }
Example #9
Source File: CustomJwtAuthenticationConverter.java From syhthems-platform with MIT License | 6 votes |
@SuppressWarnings("Duplicates") private Collection<String> getScopes(Jwt jwt) { for ( String attributeName : WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES ) { Object scopes = jwt.getClaims().get(attributeName); if (scopes instanceof String) { if (StringUtils.hasText((String) scopes)) { return Arrays.asList(((String) scopes).split(" ")); } else { return Collections.emptyList(); } } else if (scopes instanceof Collection) { return (Collection<String>) scopes; } } return Collections.emptyList(); }
Example #10
Source File: CarServiceApplicationTests.java From java-microservices-examples with Apache License 2.0 | 6 votes |
@Test public void testAddCar() { Car buggy = new Car(UUID.randomUUID(), "ID. BUGGY", LocalDate.of(2022, Month.DECEMBER, 1)); Jwt jwt = jwt(); when(this.jwtDecoder.decode(anyString())).thenReturn(Mono.just(jwt)); webTestClient.post().uri("/cars") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8) .headers(addJwt(jwt)) .body(Mono.just(buggy), Car.class) .exchange() .expectStatus().isCreated() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody() .jsonPath("$.id").isNotEmpty() .jsonPath("$.name").isEqualTo("ID. BUGGY"); }
Example #11
Source File: JwtGeneratorTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void testTokenWithCustomClaimsAndHeaders() { JwtGenerator jwtGenerator = new JwtGenerator("clientId", "subdomain", "tenantId"); JWTClaimsSet.Builder builder = jwtGenerator.getBasicClaimSet(); builder.claim(TokenClaims.CLAIM_USER_NAME, "new_testuser"); Map<String, String> map = jwtGenerator.getBasicHeaders(); Jwt jwt = JwtGenerator.createFromClaims(builder.build(), map); assertThat(jwt.getHeaders(), hasEntry(TokenHeaders.JKU, "http://localhost:33195/subdomain/token_keys")); assertThat(jwt.getHeaders(), hasEntry(TokenHeaders.KID, "legacy-token-key")); assertThat(jwt.getClaims(), hasEntry(TokenClaims.CLAIM_USER_NAME, "new_testuser")); }
Example #12
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(Jwt jwt) { if (jwt == null) { LOG.warn("No JWT supplied, running tests are we?"); } else { if (LOG.isDebugEnabled()) { URL issuer = jwt.getIssuer(); List<String> audience = jwt.getAudience(); Object subject = jwt.getClaims().get("sub"); Object scopes = jwt.getClaims().get("scope"); Object expires = jwt.getClaims().get("exp"); LOG.debug("Authorization info: Subject: {}, scopes: {}, expires {}: issuer: {}, audience: {}", subject, scopes, expires, issuer, audience); } } }
Example #13
Source File: XsuaaJwtDecoderTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void decode_withVerficationKey() throws IOException { String token = IOUtils.resourceToString("/accessTokenRSA256WithVerificationKey.txt", StandardCharsets.UTF_8); final JwtDecoder cut = new XsuaaJwtDecoderBuilder(configurationWithVerificationKey).build(); final Jwt jwt = cut.decode(token); assertThat(jwt.getClaimAsString(TokenClaims.CLAIM_CLIENT_ID)).isEqualTo("sb-clientId!t0815"); }
Example #14
Source File: JwtGeneratorTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void testTokenFromFile() throws IOException { jwtGenerator.setJku(null).setJwtHeaderKeyId(null); Jwt jwtFromTemplate = jwtGenerator.createFromTemplate("/claims_template.txt"); String jwtTokenFromTemplate = jwtFromTemplate.getTokenValue(); Jwt jwtFromFile = JwtGenerator.createFromFile("/token_cc.txt"); assertThat(jwtTokenFromTemplate, equalTo(jwtFromFile.getTokenValue())); }
Example #15
Source File: XsuaaAudienceValidatorTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void testOtherGrantedClientIdWithoutAudienceAndMatchingScopes() { List<String> scopes = new ArrayList<String>(); scopes.add("test3!t1.Display"); claimsBuilder.claim(TokenClaims.CLAIM_SCOPES, scopes); Jwt tokenWithoutAudienceButScopes = JwtGenerator.createFromClaims(claimsBuilder.build()); OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationOtherGrantedClientId) .validate(tokenWithoutAudienceButScopes); Assert.assertTrue(result.hasErrors()); List<OAuth2Error> errors = new ArrayList<>(result.getErrors()); String expectedDescription = "Jwt token with allowed audiences [test3!t1] matches none of these: [test2!t1]"; Assert.assertThat(errors.get(0).getDescription(), is(expectedDescription)); Assert.assertThat(errors.get(0).getErrorCode(), is(OAuth2ErrorCodes.INVALID_CLIENT)); }
Example #16
Source File: JwtGeneratorTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public void testTokenWithDerivedAudienceClaim() { Jwt jwt = jwtGenerator.addScopes("openid", "app1.scope", "app2.sub.scope", "app2.scope", ".scopeWithoutAppId") .deriveAudiences(true) .getToken(); assertThat(jwt.getAudience().size(), equalTo(2)); assertThat(jwt.getAudience(), hasItem("app1")); assertThat(jwt.getAudience(), hasItem("app2")); }
Example #17
Source File: XsuaaMockAutoConfigurationTest.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Test public final void autoConfigurationWithoutJwtOnClasspathInactive() { contextRunner.withClassLoader(new FilteredClassLoader(Jwt.class)) // removes Jwt.class from classpath .run((context) -> { assertThat(context.containsBean("xsuaaServiceConfiguration"), is(false)); }); }
Example #18
Source File: ExampleController.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@RequestMapping("/topsecret") public String secured() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof Jwt) { Jwt jwt = (Jwt) authentication.getPrincipal(); return String.format("You are [%s] with e-mail address [%s].%n", jwt.getSubject(), jwt.getClaimAsString("email")); } else { return "Something went wrong; authentication is not provided by IAP/JWT.\n"; } }
Example #19
Source File: AudienceValidatorTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void testCorrectAudienceMatches() { Jwt mockJwt = Mockito.mock(Jwt.class); when(mockJwt.getAudience()).thenReturn(Arrays.asList("cats")); this.contextRunner.run((context) -> { AudienceValidator validator = context.getBean(AudienceValidator.class); assertThat(validator.validate(mockJwt).hasErrors()).isFalse(); }); }
Example #20
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } }
Example #21
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(Jwt jwt) { if (jwt == null) { LOG.warn("No JWT supplied, running tests are we?"); } else { if (LOG.isDebugEnabled()) { URL issuer = jwt.getIssuer(); List<String> audience = jwt.getAudience(); Object subject = jwt.getClaims().get("sub"); Object scopes = jwt.getClaims().get("scope"); Object expires = jwt.getClaims().get("exp"); LOG.debug("Authorization info: Subject: {}, scopes: {}, expires {}: issuer: {}, audience: {}", subject, scopes, expires, issuer, audience); } } }
Example #22
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))); }
Example #23
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } }
Example #24
Source File: IapAuthenticationAutoConfiguration.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Bean @ConditionalOnMissingBean public JwtDecoder iapJwtDecoder(IapAuthenticationProperties properties, @Qualifier("iapJwtDelegatingValidator") DelegatingOAuth2TokenValidator<Jwt> validator) { NimbusJwtDecoderJwkSupport jwkSupport = new NimbusJwtDecoderJwkSupport(properties.getRegistry(), properties.getAlgorithm()); jwkSupport.setJwtValidator(validator); return jwkSupport; }
Example #25
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } }
Example #26
Source File: FirebaseTokenValidator.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
private void validateAudience(List<OAuth2Error> errors, Jwt token) { List<String> audiences = token.getAudience(); if (audiences != null) { for (String audience : audiences) { if (audience.equals(projectId)) { return; } } } errors.add(new OAuth2Error( OAuth2ErrorCodes.INVALID_REQUEST, "This aud claim is not equal to the configured audience", "https://tools.ietf.org/html/rfc6750#section-3.1")); }
Example #27
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 #28
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } }
Example #29
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(Jwt jwt) { if (jwt == null) { LOG.warn("No JWT supplied, running tests are we?"); } else { if (LOG.isDebugEnabled()) { URL issuer = jwt.getIssuer(); List<String> audience = jwt.getAudience(); Object subject = jwt.getClaims().get("sub"); Object scopes = jwt.getClaims().get("scope"); Object expires = jwt.getClaims().get("exp"); LOG.debug("Authorization info: Subject: {}, scopes: {}, expires {}: issuer: {}, audience: {}", subject, scopes, expires, issuer, audience); } } }
Example #30
Source File: ProductCompositeServiceImpl.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 5 votes |
private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } }