Java Code Examples for org.springframework.security.oauth2.core.OAuth2Error

The following examples show how to use org.springframework.security.oauth2.core.OAuth2Error. These examples are extracted from open source projects. 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
@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
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
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 4
@Override
public OAuth2AccessTokenResponse getTokenResponse(JwtBearerGrantRequest jwtBearerGrantRequest) {
	Assert.notNull(jwtBearerGrantRequest, "jwtBearerGrantRequest cannot be null");

	RequestEntity<?> request = this.requestEntityConverter.convert(jwtBearerGrantRequest);

	ResponseEntity<OAuth2AccessTokenResponse> response;
	try {
		response = this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
	} catch (RestClientException ex) {
		OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
				"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null);
		throw new OAuth2AuthorizationException(oauth2Error, ex);
	}

	OAuth2AccessTokenResponse tokenResponse = response.getBody();

	if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
		// As per spec, in Section 5.1 Successful Access Token Response
		// https://tools.ietf.org/html/rfc6749#section-5.1
		// If AccessTokenResponse.scope is empty, then default to the scope
		// originally requested by the client in the Token Request
		tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse)
				.scopes(jwtBearerGrantRequest.getClientRegistration().getScopes())
				.build();
	}

	return tokenResponse;
}
 
Example 5
@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 6
@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 7
Source Project: spring-cloud-gcp   Source File: FirebaseTokenValidator.java    License: 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 8
Source Project: spring-cloud-gcp   Source File: FirebaseTokenValidator.java    License: 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 9
Source Project: spring-cloud-gcp   Source File: FirebaseTokenValidator.java    License: 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 10
Source Project: spring-cloud-gcp   Source File: FirebaseTokenValidator.java    License: 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 11
Source Project: spring-cloud-gcp   Source File: FirebaseTokenValidator.java    License: 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 12
Source Project: jhipster-registry   Source File: AuthorizationHeaderUtil.java    License: 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();
}
 
Example 13
@Override
public TokenResponseAttributes exchange(
    AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken)
    throws OAuth2AuthenticationException {

    ClientRegistration clientRegistration = authorizationCodeAuthenticationToken.getClientRegistration();

    AuthorizationCode authorizationCode = new AuthorizationCode(
        authorizationCodeAuthenticationToken.getAuthorizationCode());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(
        authorizationCode, URI.create(clientRegistration.getRedirectUri()));
    URI tokenUri = URI.create(clientRegistration.getProviderDetails().getTokenUri());

    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    ClientAuthentication clientAuthentication = new ClientSecretGet(clientId, clientSecret);

    try {
        HTTPRequest httpRequest = createTokenRequest(
                clientRegistration, authorizationCodeGrant,
                tokenUri, clientAuthentication);

        TokenResponse tokenResponse = TokenResponse.parse(httpRequest.send());

        if (!tokenResponse.indicatesSuccess()) {
            OAuth2Error errorObject = new OAuth2Error("invalid_token_response");
            throw new OAuth2AuthenticationException(errorObject, "error");
        }

        return createTokenResponse((AccessTokenResponse) tokenResponse);

    } catch (MalformedURLException e) {
        throw new SerializeException(e.getMessage(), e);
    } catch (ParseException pe) {
        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token_response"), pe);
    } catch (IOException ioe) {
        throw new AuthenticationServiceException(
            "An error occurred while sending the Access Token Request: " +
            ioe.getMessage(), ioe);
    }

}