Search in sources :

Example 66 with OAuth2AuthorizedClient

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

the class OAuth2AuthorizedClientProviderBuilderTests method buildWhenAllProvidersThenProvidersAuthorize.

@Test
public void buildWhenAllProvidersThenProvidersAuthorize() {
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken((configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient)).clientCredentials((configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient)).password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).build();
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    // authorization_code
    // @formatter:off
    OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(this.principal).build();
    // @formatter:on
    assertThatExceptionOfType(ClientAuthorizationRequiredException.class).isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
    // refresh_token
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
    OAuth2AuthorizationContext refreshTokenContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(refreshTokenContext);
    assertThat(reauthorizedClient).isNotNull();
    verify(this.accessTokenClient, times(1)).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
    // client_credentials
    // @formatter:off
    OAuth2AuthorizationContext clientCredentialsContext = OAuth2AuthorizationContext.withClientRegistration(TestClientRegistrations.clientCredentials().build()).principal(this.principal).build();
    // @formatter:on
    authorizedClient = authorizedClientProvider.authorize(clientCredentialsContext);
    assertThat(authorizedClient).isNotNull();
    verify(this.accessTokenClient, times(2)).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
    // password
    // @formatter:off
    OAuth2AuthorizationContext passwordContext = OAuth2AuthorizationContext.withClientRegistration(TestClientRegistrations.password().build()).principal(this.principal).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").build();
    // @formatter:on
    authorizedClient = authorizedClientProvider.authorize(passwordContext);
    assertThat(authorizedClient).isNotNull();
    verify(this.accessTokenClient, times(3)).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DefaultRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient) DefaultClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) RequestEntity(org.springframework.http.RequestEntity) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) RestOperations(org.springframework.web.client.RestOperations) Mockito.times(org.mockito.Mockito.times) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) HttpStatus(org.springframework.http.HttpStatus) DefaultPasswordTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultPasswordTokenResponseClient) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) ResponseEntity(org.springframework.http.ResponseEntity) Authentication(org.springframework.security.core.Authentication) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) Mockito.mock(org.mockito.Mockito.mock) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test)

Example 67 with OAuth2AuthorizedClient

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

the class PasswordOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize.

// gh-7511
@Test
public void authorizeWhenPasswordAndAuthorizedAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
    Instant now = Instant.now();
    Instant issuedAt = now.minus(Duration.ofMinutes(60));
    Instant expiresAt = now.plus(Duration.ofMinutes(1));
    OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), // without refresh
    expiresInOneMinAccessToken);
    // token
    // Shorten the lifespan of the access token by 90 seconds, which will ultimately
    // force it to expire on the client
    this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
    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
    OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(reauthorizedClient.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 68 with OAuth2AuthorizedClient

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

the class PasswordOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize.

@Test
public void authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize() {
    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(), accessToken, // with
    TestOAuth2RefreshTokens.refreshToken());
    // refresh
    // token
    // @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
    assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 69 with OAuth2AuthorizedClient

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

the class R2dbcReactiveOAuth2AuthorizedClientServiceTests method removeAuthorizedClientWhenExistsThenRemoved.

@Test
public void removeAuthorizedClientWhenExistsThenRemoved() {
    Authentication principal = createPrincipal();
    OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
    this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal).as(StepVerifier::create).verifyComplete();
    this.authorizedClientService.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()).as(StepVerifier::create).assertNext((dbAuthorizedClient) -> assertThat(dbAuthorizedClient).isNotNull()).verifyComplete();
    this.authorizedClientService.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()).as(StepVerifier::create).verifyComplete();
    this.authorizedClientService.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()).as(StepVerifier::create).expectNextCount(0).verifyComplete();
}
Also used : ConnectionFactory(io.r2dbc.spi.ConnectionFactory) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClassPathResource(org.springframework.core.io.ClassPathResource) ConnectionFactoryInitializer(org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) DatabaseClient(org.springframework.r2dbc.core.DatabaseClient) HashSet(java.util.HashSet) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Result(io.r2dbc.spi.Result) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) Mono(reactor.core.publisher.Mono) CompositeDatabasePopulator(org.springframework.r2dbc.connection.init.CompositeDatabasePopulator) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) ResourceDatabasePopulator(org.springframework.r2dbc.connection.init.ResourceDatabasePopulator) Test(org.junit.jupiter.api.Test) Flux(reactor.core.publisher.Flux) H2ConnectionFactory(io.r2dbc.h2.H2ConnectionFactory) Authentication(org.springframework.security.core.Authentication) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Authentication(org.springframework.security.core.Authentication) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Example 70 with OAuth2AuthorizedClient

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

the class JwtBearerOAuth2AuthorizedClientProviderTests method authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize.

@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).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)

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