use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project spring-security by spring-projects.
the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.
@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
// Build the authorization code grant request for the token endpoint
AuthorizationCode authorizationCode = new AuthorizationCode(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
URI redirectUri = toURI(authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, redirectUri);
URI tokenUri = toURI(clientRegistration.getProviderDetails().getTokenUri());
// Set the credentials to authenticate the client at the token endpoint
ClientID clientId = new ClientID(clientRegistration.getClientId());
Secret clientSecret = new Secret(clientRegistration.getClientSecret());
boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod()) || ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret) : new ClientSecretBasic(clientId, clientSecret);
com.nimbusds.oauth2.sdk.TokenResponse tokenResponse = getTokenResponse(authorizationCodeGrant, tokenUri, clientAuthentication);
if (!tokenResponse.indicatesSuccess()) {
TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
ErrorObject errorObject = tokenErrorResponse.getErrorObject();
throw new OAuth2AuthorizationException(getOAuthError(errorObject));
}
AccessTokenResponse accessTokenResponse = (AccessTokenResponse) tokenResponse;
String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
// 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 Authorization Request
Set<String> scopes = getScopes(authorizationGrantRequest, accessTokenResponse);
String refreshToken = null;
if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
}
Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken).tokenType(accessTokenType).expiresIn(expiresIn).scopes(scopes).refreshToken(refreshToken).additionalParameters(additionalParameters).build();
// @formatter:on
}
use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project spring-security by spring-projects.
the class OAuth2AuthorizationCodeAuthenticationProvider method authenticate.
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
if (authorizationResponse.statusError()) {
throw new OAuth2AuthorizationException(authorizationResponse.getError());
}
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
throw new OAuth2AuthorizationException(oauth2Error);
}
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange()));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters());
authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
return authenticationResult;
}
use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project spring-security by spring-projects.
the class DefaultReactiveOAuth2AuthorizedClientManagerTests method authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient.
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).build();
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.error(exception));
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()).isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.
the class UaaAuthorizationHeaderUtil method getAuthorizationHeader.
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)));
}
use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.
the class AuthorizationHeaderUtil method getAuthorizationHeader.
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();
}
Aggregations