Search in sources :

Example 1 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeReactiveAuthenticationManager method authenticate.

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
    return Mono.defer(() -> {
        OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
        OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange().getAuthorizationResponse();
        if (authorizationResponse.statusError()) {
            return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError()));
        }
        OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange().getAuthorizationRequest();
        if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
            return Mono.error(new OAuth2AuthorizationException(oauth2Error));
        }
        OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(token.getClientRegistration(), token.getAuthorizationExchange());
        return this.accessTokenResponseClient.getTokenResponse(authzRequest).map(onSuccess(token));
    });
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 2 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken 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 3 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken 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 4 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantWebFilter method onAuthenticationSuccess.

private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
    OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(authenticationResult.getClientRegistration(), authenticationResult.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
    // @formatter:off
    return this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication).then(ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).defaultIfEmpty(this.anonymousToken).flatMap((principal) -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, webFilterExchange.getExchange())));
// @formatter:on
}
Also used : OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) WebFilter(org.springframework.web.server.WebFilter) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) WebSessionServerRequestCache(org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache) AuthenticationException(org.springframework.security.core.AuthenticationException) URI(java.net.URI) AuthorizationRequestRepository(org.springframework.security.oauth2.client.web.AuthorizationRequestRepository) LinkedHashSet(java.util.LinkedHashSet) WebFilterChain(org.springframework.web.server.WebFilterChain) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Set(java.util.Set) Mono(reactor.core.publisher.Mono) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Objects(java.util.Objects) List(java.util.List) SecurityContext(org.springframework.security.core.context.SecurityContext) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Authentication(org.springframework.security.core.Authentication) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) ServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler) Assert(org.springframework.util.Assert) UriComponents(org.springframework.web.util.UriComponents) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

Example 5 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin.

// gh-6484
@Test
public void oauth2LoginWhenIdTokenValidationFailsThenDefaultRedirectToLogin() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    // @formatter:off
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    // @formatter:on
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken authenticationToken = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()).tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()).additionalParameters(additionalParameters).build();
    // @formatter:on
    ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
    given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
    OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
    given(jwtDecoderFactory.createDecoder(any())).willReturn((token) -> Mono.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", "/login?error");
// @formatter:on
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) HashMap(java.util.HashMap) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)22 OAuth2AuthorizationCodeAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken)19 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)19 Test (org.junit.jupiter.api.Test)16 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)12 Authentication (org.springframework.security.core.Authentication)11 Mono (reactor.core.publisher.Mono)11 HashMap (java.util.HashMap)10 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 Map (java.util.Map)9 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)9 Base64 (java.util.Base64)8 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)8 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 BDDMockito.given (org.mockito.BDDMockito.given)8