Search in sources :

Example 1 with AuthorizationGrantType

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

the class JwtBearerReactiveOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to authorize (or re-authorize) the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns an empty {@code Mono} 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 an empty {@code Mono} if
 * authorization is not supported
 */
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
    Assert.notNull(context, "context cannot be null");
    ClientRegistration clientRegistration = context.getClientRegistration();
    if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
        return Mono.empty();
    }
    OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return Mono.empty();
    }
    // @formatter:off
    return this.jwtAssertionResolver.apply(context).map((jwt) -> new JwtBearerGrantRequest(clientRegistration, jwt)).flatMap(this.accessTokenResponseClient::getTokenResponse).onErrorMap(OAuth2AuthorizationException.class, (ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex)).map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken()));
// @formatter:on
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) Instant(java.time.Instant) Function(java.util.function.Function) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Duration(java.time.Duration) Clock(java.time.Clock) WebClientReactiveJwtBearerTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveJwtBearerTokenResponseClient) Jwt(org.springframework.security.oauth2.jwt.Jwt) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assert(org.springframework.util.Assert) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest)

Example 2 with AuthorizationGrantType

use of org.springframework.security.oauth2.core.AuthorizationGrantType 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());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 3 with AuthorizationGrantType

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

the class PasswordReactiveOAuth2AuthorizedClientProvider method authorize.

/**
 * Attempt to authorize (or re-authorize) the
 * {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
 * {@code context}. Returns an empty {@code Mono} 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 an empty {@code Mono} if
 * authorization (or re-authorization) is not supported
 */
@Override
public Mono<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 Mono.empty();
    }
    String username = context.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
    String password = context.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
    if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
        return Mono.empty();
    }
    if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
        // need for re-authorization
        return Mono.empty();
    }
    if (authorizedClient != null && hasTokenExpired(authorizedClient.getAccessToken()) && authorizedClient.getRefreshToken() != null) {
        // handle the refresh
        return Mono.empty();
    }
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username, password);
    return Mono.just(passwordGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse).onErrorMap(OAuth2AuthorizationException.class, (e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(), e)).map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) WebClientReactivePasswordTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactivePasswordTokenResponseClient) Duration(java.time.Duration) Clock(java.time.Clock) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) OAuth2Token(org.springframework.security.oauth2.core.OAuth2Token) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest)

Example 4 with AuthorizationGrantType

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

the class OAuth2AuthorizedClientArgumentResolverTests method setup.

@BeforeEach
public void setup() {
    this.authentication = new TestingAuthenticationToken(this.principalName, "password");
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(this.authentication);
    SecurityContextHolder.setContext(securityContext);
    // @formatter:off
    this.registration1 = ClientRegistration.withRegistrationId("client1").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    this.registration2 = ClientRegistration.withRegistrationId("client2").clientId("client-2").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope("read", "write").tokenUri("https://provider.com/oauth2/token").build();
    this.registration3 = TestClientRegistrations.password().registrationId("client3").build();
    // @formatter:on
    this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1, this.registration2, this.registration3);
    this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().authorizationCode().refreshToken().clientCredentials().build();
    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
    this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
    this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1);
    this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2);
    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) InMemoryClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) PasswordOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider) ClientCredentialsOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with AuthorizationGrantType

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenJwtBearerClientNotAuthorizedThenExchangeToken.

@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    ClientRegistration registration = ClientRegistration.withRegistrationId("jwt-bearer").clientId("client-id").clientSecret("client-secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").tokenUri("https://example.com/oauth/token").build();
    // @formatter:on
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(registration);
    Jwt jwtAssertion = TestJwts.jwt().build();
    Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(jwtAuthentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)).build();
    this.function.filter(request, this.exchange).block();
    verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), any(), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer exchanged-token");
    assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request1.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request1)).isEmpty();
}
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) Authentication(org.springframework.security.core.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Aggregations

ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)15 Test (org.junit.jupiter.api.Test)10 BeforeEach (org.junit.jupiter.api.BeforeEach)7 Jwt (org.springframework.security.oauth2.jwt.Jwt)7 AuthorizationGrantType (org.springframework.security.oauth2.core.AuthorizationGrantType)6 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)6 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)5 ReactiveOAuth2AccessTokenResponseClient (org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient)4 Clock (java.time.Clock)3 Duration (java.time.Duration)3 Instant (java.time.Instant)3 LinkedHashMap (java.util.LinkedHashMap)3 Nullable (org.springframework.lang.Nullable)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 Authentication (org.springframework.security.core.Authentication)3 InMemoryClientRegistrationRepository (org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository)3 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)3 OAuth2Token (org.springframework.security.oauth2.core.OAuth2Token)3 Assert (org.springframework.util.Assert)3