Search in sources :

Example 91 with JWT

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

the class JwtBearerOAuth2AuthorizedClientProviderTests method authorizeWhenCustomJwtAssertionResolverSetThenUsed.

@Test
public void authorizeWhenCustomJwtAssertionResolverSetThenUsed() {
    Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver = mock(Function.class);
    given(jwtAssertionResolver.apply(any())).willReturn(this.jwtAssertion);
    this.authorizedClientProvider.setJwtAssertionResolver(jwtAssertionResolver);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    // @formatter:off
    TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    verify(jwtAssertionResolver).apply(any());
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
    assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Jwt(org.springframework.security.oauth2.jwt.Jwt) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 92 with JWT

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenJwtBearerClientNotAuthorizedThenExchangeToken.

@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
    setupMocks();
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(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(Mono.just(registration));
    Jwt jwtAssertion = TestJwts.jwt().build();
    Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()), eq(jwtAuthentication), any())).willReturn(Mono.empty());
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).build();
    // @formatter:on
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(jwtAuthentication)).subscriberContext(serverWebExchange()).block();
    verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).loadAuthorizedClient(eq(registration.getRegistrationId()), eq(jwtAuthentication), any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), 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) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 93 with JWT

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

the class SecurityMockMvcRequestPostProcessorsJwtTests method jwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication.

@Test
public void jwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() {
    jwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities")).postProcessRequest(this.request);
    verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class));
    SecurityContext context = this.contextCaptor.getValue();
    assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) FilterChainProxy(org.springframework.security.web.FilterChainProxy) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DefaultSecurityFilterChain(org.springframework.security.web.DefaultSecurityFilterChain) SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestSecurityContextHolder(org.springframework.security.test.context.TestSecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) MockServletContext(org.springframework.mock.web.MockServletContext) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityMockMvcRequestPostProcessors.jwt(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) BeanIds(org.springframework.security.config.BeanIds) WebTestUtils(org.springframework.security.test.web.support.WebTestUtils) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AnyRequestMatcher(org.springframework.security.web.util.matcher.AnyRequestMatcher) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 94 with JWT

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

the class SecurityMockMvcRequestPostProcessorsJwtTests method jwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication.

@Test
public void jwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() {
    jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities")).authorities((jwt) -> Arrays.asList(this.authority1)).postProcessRequest(this.request);
    verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class));
    SecurityContext context = this.contextCaptor.getValue();
    assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) FilterChainProxy(org.springframework.security.web.FilterChainProxy) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DefaultSecurityFilterChain(org.springframework.security.web.DefaultSecurityFilterChain) SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestSecurityContextHolder(org.springframework.security.test.context.TestSecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) MockServletContext(org.springframework.mock.web.MockServletContext) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityMockMvcRequestPostProcessors.jwt(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) BeanIds(org.springframework.security.config.BeanIds) WebTestUtils(org.springframework.security.test.web.support.WebTestUtils) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AnyRequestMatcher(org.springframework.security.web.util.matcher.AnyRequestMatcher) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 95 with JWT

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

the class SecurityMockMvcRequestPostProcessorsJwtTests method jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication.

@Test
public void jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() {
    String name = new String("user");
    jwt().jwt((jwt) -> jwt.subject(name)).postProcessRequest(this.request);
    verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class));
    SecurityContext context = this.contextCaptor.getValue();
    assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
    JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
    assertThat(token.getToken().getSubject()).isSameAs(name);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) FilterChainProxy(org.springframework.security.web.FilterChainProxy) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DefaultSecurityFilterChain(org.springframework.security.web.DefaultSecurityFilterChain) SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestSecurityContextHolder(org.springframework.security.test.context.TestSecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) MockServletContext(org.springframework.mock.web.MockServletContext) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityMockMvcRequestPostProcessors.jwt(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) BeanIds(org.springframework.security.config.BeanIds) WebTestUtils(org.springframework.security.test.web.support.WebTestUtils) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AnyRequestMatcher(org.springframework.security.web.util.matcher.AnyRequestMatcher) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10