Search in sources :

Example 1 with OAuth2AccessTokenResponse

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

the class OAuth2ClientBeanDefinitionParserTests method requestWhenAuthorizationResponseMatchThenProcess.

@Test
public void requestWhenAuthorizationResponseMatchThenProcess() throws Exception {
    this.spring.configLocations(xml("CustomConfiguration")).autowire();
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
    OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(authorizationRequest);
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get(authorizationRequest.getRedirectUri()).params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl(authorizationRequest.getRedirectUri()));
    // @formatter:on
    ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
    verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), any(), any(), any());
    OAuth2AuthorizedClient authorizedClient = authorizedClientCaptor.getValue();
    assertThat(authorizedClient.getClientRegistration()).isEqualTo(clientRegistration);
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 2 with OAuth2AccessTokenResponse

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

the class DefaultRefreshTokenTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest) {
    Assert.notNull(refreshTokenGrantRequest, "refreshTokenGrantRequest cannot be null");
    RequestEntity<?> request = this.requestEntityConverter.convert(refreshTokenGrantRequest);
    ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
    OAuth2AccessTokenResponse tokenResponse = response.getBody();
    if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes()) || tokenResponse.getRefreshToken() == null) {
        OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse.withResponse(tokenResponse);
        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
            tokenResponseBuilder.scopes(refreshTokenGrantRequest.getAccessToken().getScopes());
        }
        if (tokenResponse.getRefreshToken() == null) {
            // Reuse existing refresh token
            tokenResponseBuilder.refreshToken(refreshTokenGrantRequest.getRefreshToken().getTokenValue());
        }
        tokenResponse = tokenResponseBuilder.build();
    }
    return tokenResponse;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)

Example 3 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse 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 4 with OAuth2AccessTokenResponse

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

the class DefaultClientCredentialsTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
    Assert.notNull(clientCredentialsGrantRequest, "clientCredentialsGrantRequest cannot be null");
    RequestEntity<?> request = this.requestEntityConverter.convert(clientCredentialsGrantRequest);
    ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
    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
        // @formatter:off
        tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse).scopes(clientCredentialsGrantRequest.getClientRegistration().getScopes()).build();
    // @formatter:on
    }
    return tokenResponse;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)

Example 5 with OAuth2AccessTokenResponse

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

the class DefaultPasswordTokenResponseClient method getTokenResponse.

@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2PasswordGrantRequest passwordGrantRequest) {
    Assert.notNull(passwordGrantRequest, "passwordGrantRequest cannot be null");
    RequestEntity<?> request = this.requestEntityConverter.convert(passwordGrantRequest);
    ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
    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(passwordGrantRequest.getClientRegistration().getScopes()).build();
    }
    return tokenResponse;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)131 Test (org.junit.jupiter.api.Test)121 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)42 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)40 Instant (java.time.Instant)37 HashMap (java.util.HashMap)32 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)27 Mono (reactor.core.publisher.Mono)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)15 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)15 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 Authentication (org.springframework.security.core.Authentication)12 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11