Search in sources :

Example 96 with JWT

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

the class SecurityMockServerConfigurersJwtTests method mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication.

@Test
public void mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() {
    this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities"))).get().exchange().expectStatus().isOk();
    SecurityContext context = this.securityContextController.removeSecurityContext();
    assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Arrays(java.util.Arrays) HttpHeaders(org.springframework.http.HttpHeaders) CurrentSecurityContextArgumentResolver(org.springframework.security.web.reactive.result.method.annotation.CurrentSecurityContextArgumentResolver) MediaType(org.springframework.http.MediaType) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) List(java.util.List) SecurityContext(org.springframework.security.core.context.SecurityContext) Jwt(org.springframework.security.oauth2.jwt.Jwt) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 97 with JWT

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

the class SecurityMockServerConfigurersJwtTests method mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication.

@Test
public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() {
    Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build();
    this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken)).get().exchange().expectStatus().isOk();
    SecurityContext context = this.securityContextController.removeSecurityContext();
    assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
    JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
    assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
    assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token");
    assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1");
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) SecurityContext(org.springframework.security.core.context.SecurityContext) Test(org.junit.jupiter.api.Test)

Example 98 with JWT

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

the class OidcAuthorizationCodeAuthenticationProvider method createOidcToken.

private OidcIdToken createOidcToken(ClientRegistration clientRegistration, OAuth2AccessTokenResponse accessTokenResponse) {
    JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
    Jwt jwt = getJwt(accessTokenResponse, jwtDecoder);
    OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims());
    return idToken;
}
Also used : OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder)

Example 99 with JWT

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

the class JwtAuthenticationProvider method authenticate.

/**
 * Decode and validate the
 * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer
 * Token</a>.
 * @param authentication the authentication request object.
 * @return A successful authentication
 * @throws AuthenticationException if authentication failed for some reason
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
    Jwt jwt = getJwt(bearer);
    AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt);
    token.setDetails(bearer.getDetails());
    this.logger.debug("Authenticated token");
    return token;
}
Also used : AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken)

Example 100 with JWT

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

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient.

@Test
public void authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).refreshToken("refresh-token").build();
    // @formatter:on
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
    claims.put(IdTokenClaimNames.SUB, "rob");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
    given(this.userService.loadUser(any())).willReturn(Mono.just(user));
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(authorizationCodeAuthentication).block();
    assertThat(result.getPrincipal()).isEqualTo(user);
    assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
    assertThat(result.isAuthenticated()).isTrue();
    assertThat(result.getRefreshToken().getTokenValue()).isNotNull();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Mock(org.mockito.Mock) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JwtException(org.springframework.security.oauth2.jwt.JwtException) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HashMap(java.util.HashMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) 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