Search in sources :

Example 41 with OAuth2AuthorizationContext

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

the class DefaultOAuth2AuthorizedClientManagerTests method reauthorizeWhenUnsupportedProviderThenNotReauthorized.

@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
    // @formatter:off
    OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient).principal(this.principal).attributes((attrs) -> {
        attrs.put(HttpServletRequest.class.getName(), this.request);
        attrs.put(HttpServletResponse.class.getName(), this.response);
    }).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    assertThat(authorizedClient).isSameAs(this.authorizedClient);
    verifyNoInteractions(this.authorizationSuccessHandler);
    verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class), eq(this.principal), eq(this.request), eq(this.response));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 42 with OAuth2AuthorizationContext

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

the class JwtBearerOAuth2AuthorizedClientProvider 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#JWT_BEARER
 * jwt-bearer} OR the {@link OAuth2AuthorizedClient#getAccessToken() access token} is
 * not expired.
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
 * supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
        return null;
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return null;
    }
    Jwt jwt = this.jwtAssertionResolver.apply(context);
    if (jwt == null) {
        return null;
    }
    // As per spec, in section 4.1 Using Assertions as Authorization Grants
    // https://tools.ietf.org/html/rfc7521#section-4.1
    // 
    // An assertion used in this context is generally a short-lived
    // representation of the authorization grant, and authorization servers
    // SHOULD NOT issue access tokens with a lifetime that exceeds the
    // validity period of the assertion by a significant period. In
    // practice, that will usually mean that refresh tokens are not issued
    // in response to assertion grant requests, and access tokens will be
    // issued with a reasonably short lifetime. Clients can refresh an
    // expired access token by requesting a new one using the same
    // assertion, if it is still valid, or with a new assertion.
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt);
    OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, jwtBearerGrantRequest);
    return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 43 with OAuth2AuthorizationContext

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

the class PasswordOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndNotAuthorizedThenAuthorize.

@Test
public void authorizeWhenPasswordAndNotAuthorizedThenAuthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Test(org.junit.jupiter.api.Test)

Example 44 with OAuth2AuthorizationContext

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

the class PasswordOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize.

@Test
public void authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-expired", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), // without refresh token
    accessToken);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").principal(this.principal).build();
    // @formatter:on
    authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 45 with OAuth2AuthorizationContext

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

the class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize.

@Test
public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("new-refresh-token").build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(this.authorizedClient).principal(this.principal).build();
    OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
    assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)67 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)31 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)30 Instant (java.time.Instant)21 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)21 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)21 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)19 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)17 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)15 Authentication (org.springframework.security.core.Authentication)14 Function (java.util.function.Function)11 ClientAuthorizationException (org.springframework.security.oauth2.client.ClientAuthorizationException)11 Map (java.util.Map)10 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)10 HashMap (java.util.HashMap)9 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)9 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)9 BeforeEach (org.junit.jupiter.api.BeforeEach)9