Search in sources :

Example 91 with OAuth2AuthorizedClient

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

the class OAuth2ClientConfigurationTests method requestWhenAuthorizedClientManagerConfiguredThenUsed.

// gh-8700
@Test
public void requestWhenAuthorizedClientManagerConfiguredThenUsed() throws Exception {
    String clientRegistrationId = "client1";
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().registrationId(clientRegistrationId).build();
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName, TestOAuth2AccessTokens.noScopes());
    given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);
    OAuth2AuthorizedClientManagerRegisteredConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
    OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
    OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager;
    this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
    MockHttpServletRequestBuilder authenticatedRequest = get("/authorized-client").with(authentication(authentication));
    // @formatter:off
    this.mockMvc.perform(authenticatedRequest).andExpect(status().isOk()).andExpect(content().string("resolved"));
    // @formatter:on
    verify(authorizedClientManager).authorize(any());
    verifyNoInteractions(clientRegistrationRepository);
    verifyNoInteractions(authorizedClientRepository);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Test(org.junit.jupiter.api.Test)

Example 92 with OAuth2AuthorizedClient

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

the class OAuth2ClientConfigurationTests method requestWhenAuthorizedClientFoundThenMethodArgumentResolved.

@Test
public void requestWhenAuthorizedClientFoundThenMethodArgumentResolved() throws Exception {
    String clientRegistrationId = "client1";
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().registrationId(clientRegistrationId).build();
    given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId))).willReturn(clientRegistration);
    OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
    given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
    given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication), any(HttpServletRequest.class))).willReturn(authorizedClient);
    OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
    given(authorizedClient.getAccessToken()).willReturn(accessToken);
    OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
    this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
    // @formatter:off
    this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk()).andExpect(content().string("resolved"));
    // @formatter:on
    verifyZeroInteractions(accessTokenResponseClient);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Test(org.junit.jupiter.api.Test)

Example 93 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient 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 94 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient 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 95 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient 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)

Aggregations

Test (org.junit.jupiter.api.Test)140 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)123 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)66 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)51 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)45 Instant (java.time.Instant)43 Authentication (org.springframework.security.core.Authentication)41 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)36 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)34 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)32 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)31 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)31 BeforeEach (org.junit.jupiter.api.BeforeEach)28 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)23 Map (java.util.Map)21 HashMap (java.util.HashMap)20 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)17 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)17