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);
}
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);
}
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());
}
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());
}
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());
}
Aggregations