org.springframework.security.oauth2.core.OAuth2TokenValidator Java Examples

The following examples show how to use org.springframework.security.oauth2.core.OAuth2TokenValidator. 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 vote down vote up
@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 #2
Source File: IapAuthenticationAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void refreshFlowTests()  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 = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	decoder.decode(signedJWT.serialize());
	decoder.decode(signedJWT.serialize());
	verify(operations, times(1)).exchange(eq("https://spring.local"),
			eq(HttpMethod.GET),
			isNull(),
			eq(new ParameterizedTypeReference<Map<String, String>>() { }));
}
 
Example #10
Source File: ReactiveXsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void signedTokenTests() 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());
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mockRestOperations(), "https://spring.local", validator);
	decoder.decode(signedJWT.serialize());
}
 
Example #13
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: FirebaseAuthenticationAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "firebaseJwtDelegatingValidator")
public DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator(JwtIssuerValidator jwtIssuerValidator, GcpProjectIdProvider gcpProjectIdProvider) {
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(jwtIssuerValidator);
	validators.add(new FirebaseTokenValidator(projectId));
	return new DelegatingOAuth2TokenValidator<>(validators);
}
 
Example #15
Source File: XsuaaJwtDecoder.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
XsuaaJwtDecoder(XsuaaServiceConfiguration xsuaaServiceConfiguration, int cacheValidityInSeconds, int cacheSize,
		OAuth2TokenValidator<Jwt> tokenValidators, Collection<PostValidationAction> postValidationActions) {

	this.cache = Caffeine.newBuilder().expireAfterWrite(cacheValidityInSeconds, TimeUnit.SECONDS)
			.maximumSize(cacheSize)
			.build();
	this.tokenValidators = tokenValidators;
	this.xsuaaServiceConfiguration = xsuaaServiceConfiguration;

	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.postValidationActions = postValidationActions != null ? postValidationActions : Collections.emptyList();
}
 
Example #16
Source File: FirebaseJwtTokenDecoder.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
public FirebaseJwtTokenDecoder(RestOperations restClient, String googlePublicKeysEndpoint, OAuth2TokenValidator<Jwt> tokenValidator) {
	this.restClient = restClient;
	this.googlePublicKeysEndpoint = googlePublicKeysEndpoint;
	this.tokenValidator = tokenValidator;
}
 
Example #17
Source File: XsuaaJwtDecoderBuilder.java    From cloud-security-xsuaa-integration with Apache License 2.0 2 votes vote down vote up
/**
 * Configures clone token validator, in case of two xsuaa bindings (application
 * and broker plan).
 *
 * @param tokenValidators
 *            the token validators
 * @return this
 */
public XsuaaJwtDecoderBuilder withTokenValidators(OAuth2TokenValidator<Jwt>... tokenValidators) {
	xsuaaTokenValidators = Arrays.asList(tokenValidators);
	return this;
}