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

The following examples show how to use org.springframework.security.oauth2.core.OAuth2ErrorCodes. 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: 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 #2
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
public String getAuthorizationHeader() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Optional<OAuth2AuthorizedClient> client = Optional.ofNullable(
            clientRegistrationService.loadAuthorizedClient(CLIENT_REGISTRATION_ID, authentication.getName()));

        if (!client.isPresent() || client.get().getAccessToken() == null) {
            log.info("AccessToken not found, refreshing automatically");
            client = refreshAuthorizedClient(authentication);
        } else if (isExpired(client.get().getAccessToken())) {
            log.info("AccessToken expired, refreshing automatically");
            client = refreshAuthorizedClient(authentication);
        }

        return client.map(OAuth2AuthorizedClient::getAccessToken)
            .map(this::toAuthorizationHeaderValue)
            .orElseThrow(() -> new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, "Unable to get access token for user", null)));
    }
 
Example #3
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 #4
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 #5
Source File: FirebaseTokenValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void validateIssuedAt(List<OAuth2Error> errors, Jwt token) {
	Instant issuedAt = token.getIssuedAt();
	if (issuedAt == null || Instant.now(this.clock).plus(clockSkew).isBefore(issuedAt)) {
		errors.add(new OAuth2Error(
				OAuth2ErrorCodes.INVALID_REQUEST,
				String.format("iat claim header must be in the past"),
				"https://tools.ietf.org/html/rfc6750#section-3.1"));
	}
}
 
Example #6
Source File: FirebaseTokenValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void validateSubject(List<OAuth2Error> errors, Jwt token) {
	String subject = token.getSubject();
	if (subject == null || subject.length() == 0) {
		errors.add(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST,
				"sub claim can not be empty",
				"https://tools.ietf.org/html/rfc6750#section-3.1"
				));
	}
}
 
Example #7
Source File: FirebaseTokenValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void validateAuthTime(List<OAuth2Error> errors, Jwt token) {
	Instant authTime = token.getClaimAsInstant("auth_time");
	if (authTime == null || Instant.now(this.clock).plus(clockSkew).isBefore(authTime)) {
		errors.add(new OAuth2Error(
				OAuth2ErrorCodes.INVALID_REQUEST,
				String.format("auth_time claim header must be in the past"),
				"https://tools.ietf.org/html/rfc6750#section-3.1"));
	}
}
 
Example #8
Source File: FirebaseTokenValidator.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    String name = oauthToken.getName();
    String registrationId = oauthToken.getAuthorizedClientRegistrationId();
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(registrationId, name);

    if (null == client) {
        throw new OAuth2AuthorizationException(new OAuth2Error("access_denied", "The token is expired", null));
    }
    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken != null) {
        String tokenType = accessToken.getTokenType().getValue();
        String accessTokenValue = accessToken.getTokenValue();
        if (isExpired(accessToken)) {
            log.info("AccessToken expired, refreshing automatically");
            accessTokenValue = refreshToken(client, oauthToken);
            if (null == accessTokenValue) {
                SecurityContextHolder.getContext().setAuthentication(null);
                throw new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, "The token is expired", null));
            }
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessTokenValue);
        return Optional.of(authorizationHeaderValue);
    }
    return Optional.empty();
}