Search in sources :

Example 16 with OAuth2AccessTokenResponse

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredThenRefresh.

@Test
public void filterWhenRefreshRequiredThenRefresh() {
    setupMocks();
    OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
    given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response));
    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);
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
    // @formatter:on
    TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
    // @formatter:off
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    // @formatter:on
    verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(authentication), any());
    OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
    assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
    assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(response.getRefreshToken());
    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) 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 17 with OAuth2AccessTokenResponse

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

the class OAuth2LoginBeanDefinitionParserTests method requestWhenAuthorizationResponseValidThenAuthenticate.

@Test
public void requestWhenAuthorizationResponseValidThenAuthenticate() throws Exception {
    this.spring.configLocations(this.xml("MultiClientRegistration-WithCustomConfiguration")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User oauth2User = TestOAuth2Users.create();
    given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
    // @formatter:on
    ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
    Authentication authentication = authenticationCaptor.getValue();
    assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 18 with OAuth2AccessTokenResponse

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

the class OAuth2LoginBeanDefinitionParserTests method requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled.

@Test
public void requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled() throws Exception {
    this.spring.configLocations(this.xml("SingleClientRegistration-WithJwtDecoderFactoryAndDefaultSuccessHandler")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    Jwt jwt = TestJwts.user();
    given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"));
    // @formatter:on
    verify(this.jwtDecoderFactory).createDecoder(any());
    verify(this.requestCache).getRequest(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 19 with OAuth2AccessTokenResponse

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

the class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenClientCredentialsAndTokenExpiredThenReauthorize.

@Test
public void authorizeWhenClientCredentialsAndTokenExpiredThenReauthorize() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), accessToken);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    // @formatter:on
    authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    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 20 with OAuth2AccessTokenResponse

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

the class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenClientCredentialsAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize.

// gh-7511
@Test
public void authorizeWhenClientCredentialsAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
    Instant now = Instant.now();
    Instant issuedAt = now.minus(Duration.ofMinutes(60));
    Instant expiresAt = now.minus(Duration.ofMinutes(1));
    OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), expiresInOneMinAccessToken);
    // 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(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    // @formatter:on
    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());
}
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

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