Search in sources :

Example 6 with OAuth2AccessTokenResponse

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

the class DefaultAuthorizationCodeTokenResponseClient method getTokenResponse.

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

Example 7 with OAuth2AccessTokenResponse

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

the class PasswordOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to authorize (or re-authorize) the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns {@code null} if authorization (or re-authorization) is not
 * supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
 * authorization grant type} is not {@link AuthorizationGrantType#PASSWORD password}
 * OR the {@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME username} and/or
 * {@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME password} attributes are
 * not available in the provided {@code context} OR the
 * {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
 *
 * <p>
 * The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
 * are supported:
 * <ol>
 * <li>{@link OAuth2AuthorizationContext#USERNAME_ATTRIBUTE_NAME} (required) - a
 * {@code String} value for the resource owner's username</li>
 * <li>{@link OAuth2AuthorizationContext#PASSWORD_ATTRIBUTE_NAME} (required) - a
 * {@code String} value for the resource owner's password</li>
 * </ol>
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization (or
 * re-authorization) is not supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (!AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType())) {
        return null;
    }
    String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
    String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
    if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
        return null;
    }
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return null;
    }
    if (authorizedClient != null && hasTokenExpired(authorizedClient.getAccessToken()) && authorizedClient.getRefreshToken() != null) {
        // RefreshTokenOAuth2AuthorizedClientProvider to handle the refresh
        return null;
    }
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username, password);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, passwordGrantRequest);
    return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 8 with OAuth2AccessTokenResponse

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

the class RefreshTokenOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to re-authorize the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns {@code null} if re-authorization is not supported, e.g.
 * the client is not authorized OR the {@link OAuth2AuthorizedClient#getRefreshToken()
 * refresh token} is not available for the authorized client OR the
 * {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
 *
 * <p>
 * The following {@link OAuth2AuthorizationContext#getAttributes() context attributes}
 * are supported:
 * <ol>
 * <li>{@link OAuth2AuthorizationContext#REQUEST_SCOPE_ATTRIBUTE_NAME} (optional) - a
 * {@code String[]} of scope(s) to be requested by the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client}</li>
 * </ol>
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if re-authorization is
 * not supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient == null || authorizedClient.getRefreshToken() == null || !hasTokenExpired(authorizedClient.getAccessToken())) {
        return null;
    }
    Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
    Set<String> scopes = Collections.emptySet();
    if (requestScope != null) {
        Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
        scopes = new HashSet<>(Arrays.asList((String[]) requestScope));
    }
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(authorizedClient.getClientRegistration(), authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(authorizedClient, refreshTokenGrantRequest);
    return new OAuth2AuthorizedClient(context.getAuthorizedClient().getClientRegistration(), context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 9 with OAuth2AccessTokenResponse

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsTokenExpiredThenGetNewToken.

@Test
public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() {
    setupMocks();
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    // @formatter:on
    given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName", accessToken, null);
    TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    // @formatter:on
    verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(authentication), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
    assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request1.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request1)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 10 with OAuth2AccessTokenResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken.

@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
    OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
    RestOperations refreshTokenClient = mock(RestOperations.class);
    given(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))).willReturn(new ResponseEntity(response, HttpStatus.OK));
    DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
    refreshTokenTokenResponseClient.setRestOperations(refreshTokenClient);
    RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
    authorizedClientProvider.setAccessTokenResponseClient(refreshTokenTokenResponseClient);
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
    this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(new MockHttpServletRequest())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(new MockHttpServletResponse())).build();
    this.function.filter(request, this.exchange).block();
    verify(refreshTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
    verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(this.authentication), any(), any());
    OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
    assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
    assertThat(newAuthorizedClient.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request0 = requests.get(0);
    assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
    assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request0.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request0)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Instant(java.time.Instant) DefaultRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient) ResponseEntity(org.springframework.http.ResponseEntity) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) RefreshTokenOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)134 Test (org.junit.jupiter.api.Test)122 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)43 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 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)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