Search in sources :

Example 11 with JWK

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

the class DefaultAuthorizationCodeTokenResponseClientTests 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.clientRegistration.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);
    this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration));
    RecordedRequest recordedRequest = this.server.takeRequest();
    assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    String formParameters = recordedRequest.getBody().readUtf8();
    assertThat(formParameters).contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
    assertThat(formParameters).contains("client_assertion=");
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) 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) 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) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) 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) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) HttpMethod(org.springframework.http.HttpMethod) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) 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) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockResponse(okhttp3.mockwebserver.MockResponse) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 12 with JWK

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

the class NimbusJwtEncoder method selectJwk.

private JWK selectJwk(JwsHeader headers) {
    List<JWK> jwks;
    try {
        JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers));
        jwks = this.jwkSource.get(jwkSelector, null);
    } catch (Exception ex) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key -> " + ex.getMessage()), ex);
    }
    if (jwks.size() > 1) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Found multiple JWK signing keys for algorithm '" + headers.getAlgorithm().getName() + "'"));
    }
    if (jwks.isEmpty()) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
    }
    return jwks.get(0);
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) JOSEException(com.nimbusds.jose.JOSEException) JWK(com.nimbusds.jose.jwk.JWK)

Example 13 with JWK

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

the class NimbusJwtEncoderTests method encodeWhenKeysRotatedThenNewKeyUsed.

@Test
public void encodeWhenKeysRotatedThenNewKeyUsed() throws Exception {
    TestJWKSource jwkSource = new TestJWKSource();
    JWKSource<SecurityContext> jwkSourceDelegate = spy(new JWKSource<SecurityContext>() {

        @Override
        public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) {
            return jwkSource.get(jwkSelector, context);
        }
    });
    NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSourceDelegate);
    JwkListResultCaptor jwkListResultCaptor = new JwkListResultCaptor();
    willAnswer(jwkListResultCaptor).given(jwkSourceDelegate).get(any(), any());
    JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
    JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
    Jwt encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    JWK jwk1 = jwkListResultCaptor.getResult().get(0);
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk1).toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws.getTokenValue());
    // Simulate key rotation
    jwkSource.rotate();
    encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    JWK jwk2 = jwkListResultCaptor.getResult().get(0);
    jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk2).toRSAPublicKey()).build();
    jwtDecoder.decode(encodedJws.getTokenValue());
    assertThat(jwk1.getKeyID()).isNotEqualTo(jwk2.getKeyID());
}
Also used : JWKSelector(com.nimbusds.jose.jwk.JWKSelector) RSAKey(com.nimbusds.jose.jwk.RSAKey) SecurityContext(com.nimbusds.jose.proc.SecurityContext) ArrayList(java.util.ArrayList) List(java.util.List) JWK(com.nimbusds.jose.jwk.JWK) Test(org.junit.jupiter.api.Test)

Example 14 with JWK

use of com.nimbusds.jose.jwk.JWK in project oxAuth by GluuFederation.

the class CrossEncryptionTest method decryptAndValidateSignatureWithNimbus.

private void decryptAndValidateSignatureWithNimbus(String jweString) throws ParseException, JOSEException {
    JWK jwk = JWK.parse(recipientJwkJson);
    RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
    JWEObject jweObject = JWEObject.parse(jweString);
    jweObject.decrypt(new RSADecrypter(rsaPrivateKey));
    SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
    assertNotNull("Payload not a signed JWT", signedJWT);
    RSAKey senderJWK = (RSAKey) JWK.parse(senderJwkJson);
    assertTrue(signedJWT.verify(new RSASSAVerifier(senderJWK)));
    assertEquals("testing", signedJWT.getJWTClaimsSet().getSubject());
    System.out.println("Nimbus decrypt and nested jwt signature verification succeed: " + signedJWT.getJWTClaimsSet().toJSONObject());
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 15 with JWK

use of com.nimbusds.jose.jwk.JWK in project oxAuth by GluuFederation.

the class CrossEncryptionTest method testDecryptNimbusJoseJwt.

private boolean testDecryptNimbusJoseJwt(String jwe) {
    try {
        EncryptedJWT encryptedJwt = EncryptedJWT.parse(jwe);
        // EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptWithGluu());
        // EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptWithNimbus());
        JWK jwk = JWK.parse(recipientJwkJson);
        RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
        JWEDecrypter decrypter = new RSADecrypter(rsaPrivateKey);
        decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance());
        encryptedJwt.decrypt(decrypter);
        final String decryptedPayload = new String(Base64Util.base64urldecode(encryptedJwt.getPayload().toString()));
        System.out.println("Nimbusds decrypt succeed: " + decryptedPayload);
        if (isJsonEqual(decryptedPayload, PAYLOAD)) {
            return true;
        }
    } catch (Exception e) {
        System.out.println("Nimbusds decrypt failed: " + e.getMessage());
        e.printStackTrace();
    }
    return false;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JSONException(org.json.JSONException) ParseException(java.text.ParseException) InvalidJwtException(org.gluu.oxauth.model.exception.InvalidJwtException) IOException(java.io.IOException) InvalidJweException(org.gluu.oxauth.model.exception.InvalidJweException) JWK(com.nimbusds.jose.jwk.JWK) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Aggregations

JWK (com.nimbusds.jose.jwk.JWK)44 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