Search in sources :

Example 61 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project spring-security by spring-projects.

the class JwtIssuerAuthenticationManagerResolverTests method resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager.

@Test
public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception {
    try (MockWebServer server = new MockWebServer()) {
        server.start();
        String issuer = server.url("").toString();
        // @formatter:off
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)));
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET));
        server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(JWK_SET));
        // @formatter:on
        JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer))));
        jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY));
        JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(issuer);
        Authentication token = withBearerToken(jws.serialize());
        AuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null);
        assertThat(authenticationManager).isNotNull();
        Authentication authentication = authenticationManager.authenticate(token);
        assertThat(authentication.isAuthenticated()).isTrue();
    }
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) MockResponse(okhttp3.mockwebserver.MockResponse) JSONObject(net.minidev.json.JSONObject) Authentication(org.springframework.security.core.Authentication) MockWebServer(okhttp3.mockwebserver.MockWebServer) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) Payload(com.nimbusds.jose.Payload) JWSObject(com.nimbusds.jose.JWSObject) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.jupiter.api.Test)

Example 62 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project spring-cloud-gcp by spring-cloud.

the class FirebaseJwtTokenDecoderTests method invalidAudienceTests.

@Test
public void invalidAudienceTests() throws Exception {
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").audience("123").expirationTime(Date.from(Instant.now().plusSeconds(36000))).issuer("https://securetoken.google.com/123456").issueTime(Date.from(Instant.now().minusSeconds(3600))).claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond()).build();
    SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
    List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
    validators.add(new JwtTimestampValidator());
    validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
    validators.add(new FirebaseTokenValidator("123456"));
    DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
    RestOperations operations = mockRestOperations();
    FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
    assertThatExceptionOfType(JwtException.class).isThrownBy(() -> decoder.decode(signedJWT.serialize())).withMessageStartingWith("An error occurred while attempting to decode the Jwt: This aud claim is not equal to the configured audience");
}
Also used : JwtIssuerValidator(org.springframework.security.oauth2.jwt.JwtIssuerValidator) Jwt(org.springframework.security.oauth2.jwt.Jwt) ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JwtTimestampValidator(org.springframework.security.oauth2.jwt.JwtTimestampValidator) RestOperations(org.springframework.web.client.RestOperations) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Example 63 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project spring-cloud-gcp by spring-cloud.

the class FirebaseJwtTokenDecoderTests method keyNotFoundTests.

@Test
public void keyNotFoundTests() throws Exception {
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("two").build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
    OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class);
    when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success());
    FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mockRestOperations(), "https://spring.local", validator);
    assertThatExceptionOfType(JwtException.class).isThrownBy(() -> decoder.decode(signedJWT.serialize())).withMessageStartingWith("No certificate found for key: ");
}
Also used : OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Example 64 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project spring-cloud-gcp by spring-cloud.

the class FirebaseJwtTokenDecoderTests method expiredTokenTests.

@Test
public void expiredTokenTests() throws Exception {
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().minusSeconds(3600))).build();
    SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
    List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
    validators.add(new JwtTimestampValidator());
    DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
    RestOperations operations = mockRestOperations();
    FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
    assertThatExceptionOfType(JwtException.class).isThrownBy(() -> decoder.decode(signedJWT.serialize())).withMessageStartingWith("An error occurred while attempting to decode the Jwt: Jwt expired at");
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JwtTimestampValidator(org.springframework.security.oauth2.jwt.JwtTimestampValidator) RestOperations(org.springframework.web.client.RestOperations) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Example 65 with JWSHeader

use of com.nimbusds.jose.JWSHeader in project spring-cloud-gcp by spring-cloud.

the class FirebaseJwtTokenDecoderTests method connectionErrorTests.

@Test
public void connectionErrorTests() throws Exception {
    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject").expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
    SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
    OAuth2TokenValidator validator = mock(OAuth2TokenValidator.class);
    when(validator.validate(any())).thenReturn(OAuth2TokenValidatorResult.success());
    RestOperations operations = mock(RestOperations.class);
    when(operations.exchange(eq("https://spring.local"), eq(HttpMethod.GET), isNull(), eq(new ParameterizedTypeReference<Map<String, String>>() {
    }))).thenThrow(new RestClientException("Could not connect to remote peer"));
    FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
    assertThatExceptionOfType(JwtException.class).isThrownBy(() -> decoder.decode(signedJWT.serialize())).withMessageStartingWith("Error fetching public keys");
}
Also used : OAuth2TokenValidator(org.springframework.security.oauth2.core.OAuth2TokenValidator) DelegatingOAuth2TokenValidator(org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) RestClientException(org.springframework.web.client.RestClientException) SignedJWT(com.nimbusds.jwt.SignedJWT) RestOperations(org.springframework.web.client.RestOperations) JWSHeader(com.nimbusds.jose.JWSHeader) Test(org.junit.Test)

Aggregations

JWSHeader (com.nimbusds.jose.JWSHeader)67 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)56 SignedJWT (com.nimbusds.jwt.SignedJWT)50 Test (org.junit.Test)24 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)21 JWSSigner (com.nimbusds.jose.JWSSigner)18 ArrayList (java.util.ArrayList)12 SecurityContext (org.springframework.security.core.context.SecurityContext)12 OAuth2TokenValidator (org.springframework.security.oauth2.core.OAuth2TokenValidator)12 JOSEException (com.nimbusds.jose.JOSEException)11 DelegatingOAuth2TokenValidator (org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator)10 RestOperations (org.springframework.web.client.RestOperations)10 Test (org.junit.jupiter.api.Test)9 Date (java.util.Date)8 Jwt (org.springframework.security.oauth2.jwt.Jwt)8 JSONObject (net.minidev.json.JSONObject)7 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)6 MACSigner (com.nimbusds.jose.crypto.MACSigner)6 JWK (com.nimbusds.jose.jwk.JWK)6 PrivateKey (java.security.PrivateKey)6