Search in sources :

Example 6 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project spring-security by spring-projects.

the class OAuth2ResourceServerBeanDefinitionParserTests method requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage.

@Test
public void requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage() throws Exception {
    this.spring.configLocations(xml("MockJwtValidator"), xml("Jwt")).autowire();
    mockRestOperations(jwks("Default"));
    String token = this.token("ValidNoScopes");
    OAuth2TokenValidator<Jwt> jwtValidator = this.spring.getContext().getBean(OAuth2TokenValidator.class);
    OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
    given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
    // @formatter:off
    this.mvc.perform(get("/").header("Authorization", "Bearer " + token)).andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description")));
// @formatter:on
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 7 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project spring-security by spring-projects.

the class OAuth2ResourceServerBeanDefinitionParserTests method requestWhenJwtAuthenticationConverterThenUsed.

@Test
public void requestWhenJwtAuthenticationConverterThenUsed() throws Exception {
    this.spring.configLocations(xml("MockJwtDecoder"), xml("MockJwtAuthenticationConverter"), xml("JwtAuthenticationConverter")).autowire();
    Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = (Converter<Jwt, JwtAuthenticationToken>) this.spring.getContext().getBean("jwtAuthenticationConverter");
    given(jwtAuthenticationConverter.convert(any(Jwt.class))).willReturn(new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
    JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(jwtDecoder.decode(anyString())).willReturn(TestJwts.jwt().build());
    // @formatter:off
    this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());
    // @formatter:on
    verify(jwtAuthenticationConverter).convert(any(Jwt.class));
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Converter(org.springframework.core.convert.converter.Converter) Test(org.junit.jupiter.api.Test)

Example 8 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt in project spring-security by spring-projects.

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Example 9 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt 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 10 with Jwt

use of org.springframework.security.oauth2.jwt.Jwt 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

Test (org.junit.jupiter.api.Test)139 Jwt (org.springframework.security.oauth2.jwt.Jwt)83 GrantedAuthority (org.springframework.security.core.GrantedAuthority)47 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)37 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)36 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)36 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)30 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)29 BeforeEach (org.junit.jupiter.api.BeforeEach)29 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)27 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)24 Instant (java.time.Instant)23 HttpHeaders (org.springframework.http.HttpHeaders)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)22 JwtDecoder (org.springframework.security.oauth2.jwt.JwtDecoder)22 Collections (java.util.Collections)21 MediaType (org.springframework.http.MediaType)21 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)21 MockWebServer (okhttp3.mockwebserver.MockWebServer)20 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)20