Search in sources :

Example 41 with JWT

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

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenIdTokenInvalidNonceThenOAuth2AuthenticationException.

@Test
public void authenticateWhenIdTokenInvalidNonceThenOAuth2AuthenticationException() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).build();
    // @formatter:on
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
    claims.put(IdTokenClaimNames.SUB, "sub");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
    claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
    Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block()).withMessageContaining("[invalid_nonce]");
}
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) Test(org.junit.jupiter.api.Test)

Example 42 with JWT

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

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
    ClientRegistration clientRegistration = this.registration.build();
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue());
    additionalParameters.put("param1", "value1");
    additionalParameters.put("param2", "value2");
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).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(clientRegistration.getClientId()));
    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);
    ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    this.manager.authenticate(authorizationCodeAuthentication).block();
    assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
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) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) 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) Test(org.junit.jupiter.api.Test)

Example 43 with JWT

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

the class OidcIdTokenValidatorTests method validateIdToken.

private Collection<OAuth2Error> validateIdToken() {
    // @formatter:off
    Jwt idToken = Jwt.withTokenValue("token").issuedAt(this.issuedAt).expiresAt(this.expiresAt).headers((h) -> h.putAll(this.headers)).claims((c) -> c.putAll(this.claims)).build();
    // @formatter:on
    OidcIdTokenValidator validator = new OidcIdTokenValidator(this.registration.build());
    validator.setClockSkew(this.clockSkew);
    return validator.validate(idToken).getErrors();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Collection(java.util.Collection) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test) Duration(java.time.Duration) Map(java.util.Map) JwsAlgorithms(org.springframework.security.oauth2.jose.jws.JwsAlgorithms) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Jwt(org.springframework.security.oauth2.jwt.Jwt) Collections(java.util.Collections) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Jwt(org.springframework.security.oauth2.jwt.Jwt)

Example 44 with JWT

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenPrivateKeyJwtClientAuthenticationMethodThenCustomized() throws Exception {
    RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
    given(this.jwkResolver.apply(any())).willReturn(rsaJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

Example 45 with JWT

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

the class NimbusJwtClientAuthenticationParametersConverterTests method convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized.

@Test
public void convertWhenClientSecretJwtClientAuthenticationMethodThenCustomized() {
    OctetSequenceKey secretJwk = TestJwks.DEFAULT_SECRET_JWK;
    given(this.jwkResolver.apply(any())).willReturn(secretJwk);
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).build();
    // @formatter:on
    OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
    assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE)).isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
    assertThat(encodedJws).isNotNull();
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
    Jwt jws = jwtDecoder.decode(encodedJws);
    assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName());
    assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID());
    assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
    assertThat(jws.getAudience()).isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
    assertThat(jws.getId()).isNotNull();
    assertThat(jws.getIssuedAt()).isNotNull();
    assertThat(jws.getExpiresAt()).isNotNull();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) Jwt(org.springframework.security.oauth2.jwt.Jwt) OctetSequenceKey(com.nimbusds.jose.jwk.OctetSequenceKey) 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