use of org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider 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());
}
use of org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider 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();
}
use of org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider in project spring-security by spring-projects.
the class RefreshTokenOAuth2AuthorizedClientProviderTests method setup.
@BeforeEach
public void setup() {
this.authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken expiredAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), expiredAccessToken, TestOAuth2RefreshTokens.refreshToken());
}
Aggregations