Search in sources :

Example 11 with JWT

use of com.auth0.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 12 with JWT

use of com.auth0.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)

Example 13 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled.

@Test
public void requestWhenOidcAuthenticationResponseValidThenJwtDecoderFactoryCalled() throws Exception {
    this.spring.configLocations(this.xml("SingleClientRegistration-WithJwtDecoderFactoryAndDefaultSuccessHandler")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    Jwt jwt = TestJwts.user();
    given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"));
    // @formatter:on
    verify(this.jwtDecoderFactory).createDecoder(any());
    verify(this.requestCache).getRequest(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 14 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class DelegatingJwtGrantedAuthoritiesConverterTests method convertWhenMultipleConvertersThenDuplicatesRemoved.

@Test
public void convertWhenMultipleConvertersThenDuplicatesRemoved() {
    Converter<Jwt, Collection<GrantedAuthority>> one = (jwt) -> AuthorityUtils.createAuthorityList("one", "two");
    Converter<Jwt, Collection<GrantedAuthority>> two = (jwt) -> AuthorityUtils.createAuthorityList("one", "three");
    DelegatingJwtGrantedAuthoritiesConverter composite = new DelegatingJwtGrantedAuthoritiesConverter(one, two);
    Jwt jwt = TestJwts.jwt().build();
    Collection<GrantedAuthority> authorities = composite.convert(jwt);
    assertThat(authorityListToOrderedSet(authorities)).containsExactly("one", "two", "three");
}
Also used : Test(org.junit.jupiter.api.Test) Converter(org.springframework.core.convert.converter.Converter) Collection(java.util.Collection) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) Jwt(org.springframework.security.oauth2.jwt.Jwt) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) LinkedHashSet(java.util.LinkedHashSet) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Jwt(org.springframework.security.oauth2.jwt.Jwt) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Collection(java.util.Collection) Test(org.junit.jupiter.api.Test)

Example 15 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class JwtAuthenticationProviderTests method authenticateWhenConverterReturnsAuthenticationThenProviderPropagatesIt.

@Test
public void authenticateWhenConverterReturnsAuthenticationThenProviderPropagatesIt() {
    BearerTokenAuthenticationToken token = this.authentication();
    Object details = mock(Object.class);
    token.setDetails(details);
    Jwt jwt = TestJwts.jwt().build();
    JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt);
    given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt);
    given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication);
    // @formatter:off
    assertThat(this.provider.authenticate(token)).isEqualTo(authentication).hasFieldOrPropertyWithValue("details", details);
// @formatter:on
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) Test(org.junit.jupiter.api.Test)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)96 Test (org.junit.jupiter.api.Test)78 GrantedAuthority (org.springframework.security.core.GrantedAuthority)49 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 Arrays (java.util.Arrays)17 List (java.util.List)17 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Test (org.junit.Test)14 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Authentication (org.springframework.security.core.Authentication)12 HashMap (java.util.HashMap)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 Map (java.util.Map)10 SecurityContext (org.springframework.security.core.context.SecurityContext)10 JwtAuthenticationToken (org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken)10