Search in sources :

Example 26 with OAuth2AuthorizationResponse

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

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort.

// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    String state = "state";
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setScheme("https");
    request.setServerName("example.com");
    request.setServerPort(443);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(request, response, this.registration2, state);
    this.setUpAuthenticationResult(this.registration2);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
    OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
    String expectedRedirectUri = "https://example.com/login/oauth2/code/registration-id-2";
    assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
    assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) FilterChain(jakarta.servlet.FilterChain) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 27 with OAuth2AuthorizationResponse

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

the class OAuth2AuthorizationCodeGrantFilter method processAuthorizationResponse.

private void processAuthorizationResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
    OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
    String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
    String redirectUri = UrlUtils.buildFullRequestUrl(request);
    OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri);
    OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
    authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
    try {
        authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationManager.authenticate(authenticationRequest);
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error error = ex.getError();
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri()).queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
        if (!StringUtils.isEmpty(error.getDescription())) {
            uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
        }
        if (!StringUtils.isEmpty(error.getUri())) {
            uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
        }
        this.redirectStrategy.sendRedirect(request, response, uriBuilder.build().encode().toString());
        return;
    }
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser";
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, currentAuthentication, request, response);
    String redirectUrl = authorizationRequest.getRedirectUri();
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    if (savedRequest != null) {
        redirectUrl = savedRequest.getRedirectUrl();
        this.requestCache.removeRequest(request, response);
    }
    this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest)

Example 28 with OAuth2AuthorizationResponse

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

the class OAuth2LoginAuthenticationFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
    if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) {
        OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
    if (authorizationRequest == null) {
        OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    if (clientRegistration == null) {
        OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    // @formatter:off
    String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null).build().toUriString();
    // @formatter:on
    OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri);
    Object authenticationDetails = this.authenticationDetailsSource.buildDetails(request);
    OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
    authenticationRequest.setDetails(authenticationDetails);
    OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) this.getAuthenticationManager().authenticate(authenticationRequest);
    OAuth2AuthenticationToken oauth2Authentication = this.authenticationResultConverter.convert(authenticationResult);
    Assert.notNull(oauth2Authentication, "authentication result cannot be null");
    oauth2Authentication.setDetails(authenticationDetails);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(authenticationResult.getClientRegistration(), oauth2Authentication.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);
    return oauth2Authentication;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 29 with OAuth2AuthorizationResponse

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

the class ServerOAuth2AuthorizationCodeAuthenticationTokenConverter method authenticationRequest.

private Mono<OAuth2AuthorizationCodeAuthenticationToken> authenticationRequest(ServerWebExchange exchange, OAuth2AuthorizationRequest authorizationRequest) {
    // @formatter:off
    return Mono.just(authorizationRequest).map(OAuth2AuthorizationRequest::getAttributes).flatMap((attributes) -> {
        String id = (String) attributes.get(OAuth2ParameterNames.REGISTRATION_ID);
        if (id == null) {
            return oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
        }
        return this.clientRegistrationRepository.findByRegistrationId(id);
    }).switchIfEmpty(oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE)).map((clientRegistration) -> {
        OAuth2AuthorizationResponse authorizationResponse = convertResponse(exchange);
        OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
        return authenticationRequest;
    });
// @formatter:on
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)

Example 30 with OAuth2AuthorizationResponse

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

the class OidcAuthorizationCodeReactiveAuthenticationManager method authenticate.

@Override
public Mono<Authentication> authenticate(Authentication authentication) {
    return Mono.defer(() -> {
        OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
        // value.
        if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
            // and let OAuth2LoginReactiveAuthenticationManager handle it instead
            return Mono.empty();
        }
        OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
        OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
        if (authorizationResponse.statusError()) {
            return Mono.error(new OAuth2AuthenticationException(authorizationResponse.getError(), authorizationResponse.getError().toString()));
        }
        if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
            return Mono.error(new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()));
        }
        OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange());
        return this.accessTokenResponseClient.getTokenResponse(authzRequest).flatMap((accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse)).onErrorMap(OAuth2AuthorizationException.class, (e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e)).onErrorMap(JwtException.class, (e) -> {
            OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(), null);
            return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), e);
        });
    });
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) MessageDigest(java.security.MessageDigest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) Collection(java.util.Collection) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwtException(org.springframework.security.oauth2.jwt.JwtException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Assert(org.springframework.util.Assert) 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) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Aggregations

OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)32 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)24 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)23 Test (org.junit.jupiter.api.Test)17 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)14 OAuth2AuthorizationCodeAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken)10 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)10 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)9 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)7 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)6 HashMap (java.util.HashMap)5 Authentication (org.springframework.security.core.Authentication)5 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)5 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)5 ServerAuthenticationConverter (org.springframework.security.web.server.authentication.ServerAuthenticationConverter)5 WebTestClient (org.springframework.test.web.reactive.server.WebTestClient)5 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)4 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)4 ReactiveAuthenticationManager (org.springframework.security.authentication.ReactiveAuthenticationManager)3 OidcUserRequest (org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest)3