Search in sources :

Example 1 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) {
        // and let OAuth2LoginAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
    if (authorizationResponse.statusError()) {
        throw new OAuth2AuthenticationException(authorizationResponse.getError(), authorizationResponse.getError().toString());
    }
    if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    OAuth2AccessTokenResponse accessTokenResponse = getResponse(authorizationCodeAuthentication);
    ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
    Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
    if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
        OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Missing (required) ID Token in Token Response for Client Registration: " + clientRegistration.getRegistrationId(), null);
        throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString());
    }
    OidcIdToken idToken = createOidcToken(clientRegistration, accessTokenResponse);
    validateNonce(authorizationRequest, idToken);
    OidcUser oidcUser = this.userService.loadUser(new OidcUserRequest(clientRegistration, accessTokenResponse.getAccessToken(), idToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oidcUser.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities, accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken());
    authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
    return authenticationResult;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 2 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OidcReactiveOAuth2UserService method loadUser.

@Override
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    // @formatter:off
    return getUserInfo(userRequest).map((userInfo) -> new OidcUserAuthority(userRequest.getIdToken(), userInfo)).defaultIfEmpty(new OidcUserAuthority(userRequest.getIdToken(), null)).map((authority) -> {
        OidcUserInfo userInfo = authority.getUserInfo();
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(authority);
        OAuth2AccessToken token = userRequest.getAccessToken();
        for (String scope : token.getScopes()) {
            authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
        }
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (StringUtils.hasText(userNameAttributeName)) {
            return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName);
        }
        return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
    });
// @formatter:on
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OidcUserInfo(org.springframework.security.oauth2.core.oidc.OidcUserInfo) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) HashSet(java.util.HashSet)

Example 3 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
        // and let OidcAuthorizationCodeAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
    try {
        authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange()));
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error oauth2Error = ex.getError();
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
    }
    OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken();
    Map<String, Object> additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters();
    OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
    authenticationResult.setDetails(loginAuthenticationToken.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 4 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManager method validateNonce.

private static Mono<OidcIdToken> validateNonce(OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
    String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getAttribute(OidcParameterNames.NONCE);
    if (requestNonce != null) {
        String nonceHash = getNonceHash(requestNonce);
        String nonceHashClaim = idToken.getNonce();
        if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
    }
    return Mono.just(idToken);
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 5 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenAuthorizationRequestNotFoundThenThrowAuthenticationException.

@Test
public void requestWhenAuthorizationRequestNotFoundThenThrowAuthenticationException() throws Exception {
    this.spring.configLocations(this.xml("SingleClientRegistration-WithCustomAuthenticationFailureHandler")).autowire();
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", "state123");
    this.mvc.perform(get("/login/oauth2/code/google").params(params));
    ArgumentCaptor<AuthenticationException> exceptionCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
    verify(this.authenticationFailureHandler).onAuthenticationFailure(any(), any(), exceptionCaptor.capture());
    AuthenticationException exception = exceptionCaptor.getValue();
    assertThat(exception).isInstanceOf(OAuth2AuthenticationException.class);
    assertThat(((OAuth2AuthenticationException) exception).getError().getErrorCode()).isEqualTo("authorization_request_not_found");
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)52 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)31 Test (org.junit.jupiter.api.Test)27 BearerTokenError (org.springframework.security.oauth2.server.resource.BearerTokenError)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)7 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)7 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)7 Map (java.util.Map)6 Authentication (org.springframework.security.core.Authentication)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)6 Mono (reactor.core.publisher.Mono)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Base64 (java.util.Base64)5