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

The following examples show how to use org.springframework.security.oauth2.core.OAuth2TokenValidatorResult. 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: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testFixedStringAudienceValidatorAddedWhenAvailable() throws Exception {
	when(mockJwt.getExpiresAt()).thenReturn(Instant.now().plusSeconds(10));
	when(mockJwt.getNotBefore()).thenReturn(Instant.now().minusSeconds(10));

	this.contextRunner
			.withUserConfiguration(FixedAudienceValidatorConfiguration.class)
			.run((context) -> {
				DelegatingOAuth2TokenValidator validator
						= context.getBean("iapJwtDelegatingValidator", DelegatingOAuth2TokenValidator.class);
				OAuth2TokenValidatorResult result = validator.validate(mockJwt);
				assertThat(result.hasErrors()).isTrue();
				assertThat(result.getErrors().size()).isEqualTo(2);
				assertThat(result.getErrors().stream().map(error -> error.getDescription()))
						.containsExactlyInAnyOrder(
								"The iss claim is not valid", "This aud claim is not equal to the configured audience");
			});
}
 
Example #2
Source File: XsuaaAudienceValidator.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
@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 #3
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 #4
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 #5
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@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 #6
Source File: AudienceValidator.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    List<String> audience = jwt.getAudience();
    if(audience.stream().anyMatch(allowedAudience::contains)) {
        return OAuth2TokenValidatorResult.success();
    } else {
        log.warn("Invalid audience: {}", audience);
        return OAuth2TokenValidatorResult.failure(error);
    }
}
 
Example #7
Source File: IapAuthenticationAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testIapBeansReturnedWhenBothIapWithMultipleAudiencesAndSpringSecurityConfigPresent() {
	when(mockJwt.getAudience()).thenReturn(Collections.singletonList("aud1"));

	this.contextRunner
			.withPropertyValues("spring.cloud.gcp.security.iap.audience=aud1, aud2")
			.run((context) -> {
				AudienceValidator validator
						= context.getBean(AudienceValidator.class);
				OAuth2TokenValidatorResult result = validator.validate(mockJwt);
				assertThat(result.hasErrors()).isFalse();
			});
}
 
Example #8
Source File: AudienceValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2TokenValidatorResult validate(Jwt t) {
	if (t.getAudience() != null) {
		for (String audience : audiences) {
			if (t.getAudience().contains(audience)) {
				return OAuth2TokenValidatorResult.success();
			}
		}
	}
	if (LOGGER.isWarnEnabled()) {
		LOGGER.warn(String.format(
				"Expected audience %s did not match token audience %s", this.audience, t.getAudience()));
	}
	return OAuth2TokenValidatorResult.failure(INVALID_AUDIENCE);
}
 
Example #9
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 #10
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 #11
Source File: FirebaseTokenValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
	List<OAuth2Error> errors = new LinkedList<>();
	validateAudience(errors, token);
	validateIssuedAt(errors, token);
	validateSubject(errors, token);
	validateAuthTime(errors, token);
	return OAuth2TokenValidatorResult.failure(errors);
}
 
Example #12
Source File: TokenBlackListValidator.java    From oauth2-resource with MIT License 5 votes vote down vote up
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    if (checkTokenValid(jwt.getTokenValue())) {
        return OAuth2TokenValidatorResult.success();
    } else {
        return OAuth2TokenValidatorResult.failure(error);
    }
}
 
Example #13
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenWithoutClientId() {
	claimsBuilder.claim(TokenClaims.CLAIM_CLIENT_ID, "");
	Jwt tokenWithoutClientId = JwtGenerator.createFromClaims(claimsBuilder.build());
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationSameClientId)
			.validate(tokenWithoutClientId);
	Assert.assertTrue(result.hasErrors());
}
 
Example #14
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void testOtherGrantedClientIdWithoutAudienceAndEmptyScopes() {
	claimsBuilder.claim(TokenClaims.CLAIM_SCOPES, "[]");
	Jwt tokenWithoutAudienceAndScopes = JwtGenerator.createFromClaims(claimsBuilder.build());
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationOtherGrantedClientId)
			.validate(tokenWithoutAudienceAndScopes);
	Assert.assertTrue(result.hasErrors());
}
 
Example #15
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void testOtherGrantedClientIdWithoutAudienceAndScopes() {
	Jwt tokenWithoutAudienceAndScopes = JwtGenerator.createFromClaims(claimsBuilder.build());
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationOtherGrantedClientId)
			.validate(tokenWithoutAudienceAndScopes);
	Assert.assertTrue(result.hasErrors());
}
 
Example #16
Source File: AudienceValidator.java    From auth0-spring-security5-api-sample with MIT License 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);

    if (jwt.getAudience().contains(audience)) {
        return OAuth2TokenValidatorResult.success();
    }

    return OAuth2TokenValidatorResult.failure(error);
}
 
Example #17
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void testOtherGrantedClientIdWithoutAudienceButScopes() {
	List<String> scopes = new ArrayList<String>();
	scopes.add("test2!t1.Display");
	claimsBuilder.claim(TokenClaims.CLAIM_SCOPES, scopes);

	Jwt tokenWithoutAudienceButScopes = JwtGenerator.createFromClaims(claimsBuilder.build());
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationOtherGrantedClientId)
			.validate(tokenWithoutAudienceButScopes);
	Assert.assertFalse(result.hasErrors());
}
 
Example #18
Source File: XsuaaAudienceValidatorForCloneTokenTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void cloneTokenClientId_unlike_brokerClientId_raisesError() {
	claimsBuilder.claim(TokenClaims.CLAIM_CLIENT_ID, "sb-clone1!b22|ANOTHERAPP!b12");

	OAuth2TokenValidatorResult result = cut.validate(JwtGenerator.createFromClaims(claimsBuilder.build()));
	Assert.assertTrue(result.hasErrors());

	List<OAuth2Error> errors = new ArrayList<>(result.getErrors());
	Assert.assertThat(errors.get(0).getDescription(),
			is("Jwt token with allowed audiences [] matches none of these: [test1!t1, brokerplanmasterapp!b123]"));
	Assert.assertThat(errors.get(0).getErrorCode(), is(OAuth2ErrorCodes.INVALID_CLIENT));
}
 
Example #19
Source File: XsuaaAudienceValidatorForCloneTokenTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void cloneTokenClientId_like_brokerClientId_shouldBeAccepted() {
	claimsBuilder.claim(TokenClaims.CLAIM_CLIENT_ID, "sb-clone1!b22|" + XSUAA_BROKER_XSAPPNAME);

	OAuth2TokenValidatorResult result = cut.validate(JwtGenerator.createFromClaims(claimsBuilder.build()));
	Assert.assertFalse(result.hasErrors());
}
 
Example #20
Source File: XsuaaAudienceValidatorForCloneTokenTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithClientId_like_brokerClientId_shouldBeIgnored() {
	claimsBuilder.claim(TokenClaims.CLAIM_CLIENT_ID, XSUAA_BROKER_CLIENT_ID);

	OAuth2TokenValidatorResult result = cut.validate(JwtGenerator.createFromClaims(claimsBuilder.build()));
	Assert.assertFalse(result.hasErrors());
}
 
Example #21
Source File: AudienceValidator.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    List<String> audience = jwt.getAudience();
    // Keycloak and Okta's default audiences, respectively
    if (audience.contains("account") || audience.contains("api://default")) {
        return OAuth2TokenValidatorResult.success();
    } else {
        log.warn("Invalid audience: {}", audience);
        return OAuth2TokenValidatorResult.failure(error);
    }
}
 
Example #22
Source File: AudienceValidator.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    List<String> audience = jwt.getAudience();
    // Keycloak and Okta's default audiences, respectively
    if (audience.contains("account") || audience.contains("api://default")) {
        return OAuth2TokenValidatorResult.success();
    } else {
        log.warn("Invalid audience: {}", audience);
        return OAuth2TokenValidatorResult.failure(error);
    }
}
 
Example #23
Source File: AudienceValidator.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    List<String> audience = jwt.getAudience();
    // Keycloak and Okta's default audiences, respectively
    if (audience.contains("account") || audience.contains("api://default")) {
        return OAuth2TokenValidatorResult.success();
    } else {
        log.warn("Invalid audience: {}", audience);
        return OAuth2TokenValidatorResult.failure(error);
    }
}
 
Example #24
Source File: AudienceValidator.java    From auth0-spring-security5-api-sample with MIT License 5 votes vote down vote up
public OAuth2TokenValidatorResult validate(Jwt jwt) {
    if (jwt.getAudience().contains(audience)) {
        return OAuth2TokenValidatorResult.success();
    }

    return OAuth2TokenValidatorResult.failure(error);
}
 
Example #25
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnGrantedClientId() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationUnGrantedClientId)
			.validate(tokenWithAudience);
	Assert.assertTrue(result.hasErrors());
}
 
Example #26
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testOtherGrantedClientId() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationUnGrantedClientId)
			.validate(tokenWithAudience);
	Assert.assertTrue(result.hasErrors());
}
 
Example #27
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testOtherGrantedClientIdWithoutAudienceAndDot() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(
			new DummyXsuaaServiceConfiguration("sb-test4!t1", "test4!t1")).validate(tokenWithAudience);
	Assert.assertFalse(result.hasErrors());
}
 
Example #28
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testBrokerCloneWithAudience() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationBrokerPlan)
			.validate(cloneTokenWithAudience);
	Assert.assertFalse(result.hasErrors());
}
 
Example #29
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testBrokerCloneWithoutAudience() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationBrokerPlan)
			.validate(cloneTokenWithAudience);
	Assert.assertFalse(result.hasErrors());
}
 
Example #30
Source File: XsuaaAudienceValidatorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
@Test
public void testOtherGrantedClientIdWithoutAudience() {
	OAuth2TokenValidatorResult result = new XsuaaAudienceValidator(serviceConfigurationOtherGrantedClientId)
			.validate(tokenWithoutAudience);
	Assert.assertFalse(result.hasErrors());
}