Search in sources :

Example 11 with AuthorizationGrantType

use of org.springframework.security.oauth2.core.AuthorizationGrantType in project books by aidanwhiteley.

the class UserServiceTest method configureOauth.

private void configureOauth(String clientId, String name) {
    Map<String, Object> details = new LinkedHashMap<>();
    details.put("name", name);
    details.put(name, name);
    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority("USER"));
    OAuth2User oauth2User = new DefaultOAuth2User(authorities, details, name);
    when(oauthToken.getName()).thenReturn(DUMMY);
    when(oauthToken.getAuthorizedClientRegistrationId()).thenReturn(DUMMY);
    when(oauthToken.getPrincipal()).thenReturn(oauth2User);
    OAuth2AuthorizedClient client = Mockito.mock(OAuth2AuthorizedClient.class);
    ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(DUMMY);
    builder.clientId(clientId).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).clientSecret(DUMMY).redirectUriTemplate(DUMMY).scope(DUMMY).authorizationUri(DUMMY).tokenUri(DUMMY).clientName(DUMMY);
    ClientRegistration clientReg = builder.build();
    when(client.getClientRegistration()).thenReturn(clientReg);
    when(authorisedClientService.loadAuthorizedClient(any(String.class), any(String.class))).thenReturn(client);
}
Also used : DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) LinkedHashMap(java.util.LinkedHashMap) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashSet(java.util.HashSet)

Example 12 with AuthorizationGrantType

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

the class ClientRegistrationsBeanDefinitionParser method getClientRegistrations.

private List<ClientRegistration> getClientRegistrations(Element element, ParserContext parserContext, Map<String, Map<String, String>> providers) {
    List<Element> clientRegistrationElts = DomUtils.getChildElementsByTagName(element, ELT_CLIENT_REGISTRATION);
    List<ClientRegistration> clientRegistrations = new ArrayList<>();
    for (Element clientRegistrationElt : clientRegistrationElts) {
        String registrationId = clientRegistrationElt.getAttribute(ATT_REGISTRATION_ID);
        String providerId = clientRegistrationElt.getAttribute(ATT_PROVIDER_ID);
        ClientRegistration.Builder builder = getBuilderFromIssuerIfPossible(parserContext, registrationId, providerId, providers);
        if (builder == null) {
            builder = getBuilder(parserContext, registrationId, providerId, providers);
            if (builder == null) {
                Object source = parserContext.extractSource(element);
                parserContext.getReaderContext().error(getErrorMessage(providerId, registrationId), source);
                // error on the config skip to next element
                continue;
            }
        }
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_ID)).ifPresent(builder::clientId);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_SECRET)).ifPresent(builder::clientSecret);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_AUTHENTICATION_METHOD)).map(ClientAuthenticationMethod::new).ifPresent(builder::clientAuthenticationMethod);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_AUTHORIZATION_GRANT_TYPE)).map(AuthorizationGrantType::new).ifPresent(builder::authorizationGrantType);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_REDIRECT_URI)).ifPresent(builder::redirectUri);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_SCOPE)).map(StringUtils::commaDelimitedListToSet).ifPresent(builder::scope);
        getOptionalIfNotEmpty(parserContext, clientRegistrationElt.getAttribute(ATT_CLIENT_NAME)).ifPresent(builder::clientName);
        clientRegistrations.add(builder.build());
    }
    return clientRegistrations;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList)

Example 13 with AuthorizationGrantType

use of org.springframework.security.oauth2.core.AuthorizationGrantType 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());
}
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) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 14 with AuthorizationGrantType

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

the class OAuth2ClientCredentialsGrantRequestTests method constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException.

@Test
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
    // @formatter:off
    ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("registration-1").clientId("client-1").authorizationGrantType(AuthorizationGrantType.IMPLICIT).redirectUri("https://localhost:8080/redirect-uri").authorizationUri("https://provider.com/oauth2/auth").clientName("Client 1").build();
    // @formatter:on
    assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(clientRegistration)).withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.CLIENT_CREDENTIALS");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 15 with AuthorizationGrantType

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

the class JwtBearerGrantRequestEntityConverterTests method convertWhenGrantRequestValidThenConverts.

@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").build();
    // @formatter:on
    Jwt jwtAssertion = TestJwts.jwt().build();
    JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
    RequestEntity<?> requestEntity = this.converter.convert(jwtBearerGrantRequest);
    assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
    assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
    HttpHeaders headers = requestEntity.getHeaders();
    assertThat(headers.getAccept()).contains(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
    assertThat(headers.getContentType()).isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
    assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
    MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
    assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.ASSERTION)).isEqualTo(jwtAssertion.getTokenValue());
    assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) MultiValueMap(org.springframework.util.MultiValueMap) 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