Search in sources :

Example 1 with JWK

use of com.nimbusds.jose.jwk.JWK in project java-docs-samples by GoogleCloudPlatform.

the class VerifyIapRequestHeader method getKey.

private ECPublicKey getKey(String kid, String alg) throws Exception {
    JWK jwk = keyCache.get(kid);
    if (jwk == null) {
        // update cache loading jwk public key data from url
        JWKSet jwkSet = JWKSet.load(new URL(PUBLIC_KEY_VERIFICATION_URL));
        for (JWK key : jwkSet.getKeys()) {
            keyCache.put(key.getKeyID(), key);
        }
        jwk = keyCache.get(kid);
    }
    // confirm that algorithm matches
    if (jwk != null && jwk.getAlgorithm().getName().equals(alg)) {
        return ECKey.parse(jwk.toJSONString()).toECPublicKey();
    }
    return null;
}
Also used : JWKSet(com.nimbusds.jose.jwk.JWKSet) URL(java.net.URL) JWK(com.nimbusds.jose.jwk.JWK)

Example 2 with JWK

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

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Example 3 with JWK

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

the class JwtDecoderProviderConfigurationUtils method getJWSAlgorithms.

static <C extends SecurityContext> Set<JWSAlgorithm> getJWSAlgorithms(JWKSource<C> jwkSource) {
    JWKMatcher jwkMatcher = new JWKMatcher.Builder().publicOnly(true).keyUses(KeyUse.SIGNATURE, null).keyTypes(KeyType.RSA, KeyType.EC).build();
    Set<JWSAlgorithm> jwsAlgorithms = new HashSet<>();
    try {
        List<? extends JWK> jwks = jwkSource.get(new JWKSelector(jwkMatcher), null);
        for (JWK jwk : jwks) {
            if (jwk.getAlgorithm() != null) {
                JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(jwk.getAlgorithm().getName());
                jwsAlgorithms.add(jwsAlgorithm);
            } else {
                if (jwk.getKeyType() == KeyType.RSA) {
                    jwsAlgorithms.addAll(JWSAlgorithm.Family.RSA);
                } else if (jwk.getKeyType() == KeyType.EC) {
                    jwsAlgorithms.addAll(JWSAlgorithm.Family.EC);
                }
            }
        }
    } catch (KeySourceException ex) {
        throw new IllegalStateException(ex);
    }
    Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set");
    return jwsAlgorithms;
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) KeySourceException(com.nimbusds.jose.KeySourceException) JWKMatcher(com.nimbusds.jose.jwk.JWKMatcher) HashSet(java.util.HashSet) JWK(com.nimbusds.jose.jwk.JWK)

Example 4 with JWK

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

the class WebClientReactiveRefreshTokenTokenResponseClientTests method getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationClientSecretJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "	  \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT).clientSecret(TestKeys.DEFAULT_ENCODED_SECRET_KEY).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    SecretKeySpec secretKey = new SecretKeySpec(clientRegistration.getClientSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    JWK jwk = TestJwks.jwk(secretKey).build();
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
    this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", "client_assertion=");
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) BDDMockito.given(org.mockito.BDDMockito.given) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 5 with JWK

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

the class WebClientReactiveRefreshTokenTokenResponseClientTests method getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "	  \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
    // @formatter:off
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).build();
    // @formatter:on
    // Configure Jwt client authentication converter
    JWK jwk = TestJwks.DEFAULT_RSA_JWK;
    Function<ClientRegistration, JWK> jwkResolver = (registration) -> jwk;
    configureJwtClientAuthenticationConverter(jwkResolver);
    OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
    this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", "client_assertion=");
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Function(java.util.function.Function) BDDMockito.given(org.mockito.BDDMockito.given) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) MockWebServer(okhttp3.mockwebserver.MockWebServer) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) Converter(org.springframework.core.convert.converter.Converter) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) TestKeys(org.springframework.security.oauth2.jose.TestKeys) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpHeaders(org.springframework.http.HttpHeaders) TestJwks(org.springframework.security.oauth2.jose.TestJwks) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) Instant(java.time.Instant) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) JWK(com.nimbusds.jose.jwk.JWK) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) TestOAuth2RefreshTokens(org.springframework.security.oauth2.core.TestOAuth2RefreshTokens) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Mockito.mock(org.mockito.Mockito.mock) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Aggregations

JWK (com.nimbusds.jose.jwk.JWK)41 Test (org.junit.jupiter.api.Test)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)17 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)17 StandardCharsets (java.nio.charset.StandardCharsets)16 Function (java.util.function.Function)16 SecretKeySpec (javax.crypto.spec.SecretKeySpec)16 MockResponse (okhttp3.mockwebserver.MockResponse)16 MockWebServer (okhttp3.mockwebserver.MockWebServer)16 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)16 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)16 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)16 AfterEach (org.junit.jupiter.api.AfterEach)16 BeforeEach (org.junit.jupiter.api.BeforeEach)16 HttpHeaders (org.springframework.http.HttpHeaders)16 MediaType (org.springframework.http.MediaType)16 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)16 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)16 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)16