Search in sources :

Example 31 with JWK

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

the class CrossEncryptionTest method testDecryptWithGluuDecrypter.

public boolean testDecryptWithGluuDecrypter(String jwe) {
    try {
        JWK jwk = JWK.parse(recipientJwkJson);
        RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
        JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);
        decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
        decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);
        final String decryptedPayload = decrypter.decrypt(jwe).getClaims().toJsonString().toString();
        System.out.println("Gluu decrypt succeed: " + decryptedPayload);
        if (isJsonEqual(decryptedPayload, PAYLOAD)) {
            return true;
        }
    } catch (Exception e) {
        System.out.println("Gluu decrypt failed: " + e.getMessage());
        e.printStackTrace();
    }
    return false;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) JweDecrypterImpl(org.gluu.oxauth.model.jwe.JweDecrypterImpl) 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)

Example 32 with JWK

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

the class CrossEncryptionTest method decryptAndValidateSignatureWithGluu.

private void decryptAndValidateSignatureWithGluu(String jweString) throws ParseException, JOSEException, InvalidJweException, JSONException, InvalidJwtException {
    JWK jwk = JWK.parse(recipientJwkJson);
    RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
    JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);
    decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
    decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);
    final Jwe jwe = decrypter.decrypt(jweString);
    assertEquals(JwtType.JWT, jwe.getHeader().getContentType());
    final Jwt jwt = jwe.getSignedJWTPayload();
    Assert.assertTrue(new RSASigner(SignatureAlgorithm.RS256, getSenderPublicKey()).validate(jwt));
    System.out.println("Gluu decrypt and nested jwt signature verification succeed: " + jwt.getClaims().toJsonString());
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) JweDecrypterImpl(org.gluu.oxauth.model.jwe.JweDecrypterImpl) Jwt(org.gluu.oxauth.model.jwt.Jwt) RSASigner(org.gluu.oxauth.model.jws.RSASigner) Jwe(org.gluu.oxauth.model.jwe.Jwe) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK)

Example 33 with JWK

use of com.nimbusds.jose.jwk.JWK in project dhis2-core by dhis2.

the class JwtUtils method encode.

public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException {
    Assert.notNull(headers, "headers cannot be null");
    Assert.notNull(claims, "claims cannot be null");
    JWK jwk = selectJwk(headers);
    if (jwk == null) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
    } else if (!StringUtils.hasText(jwk.getKeyID())) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "The \"kid\" (key ID) from the selected JWK cannot be empty"));
    }
    headers = JoseHeader.from(headers).type(JOSEObjectType.JWT.getType()).keyId(jwk.getKeyID()).build();
    claims = JwtClaimsSet.from(claims).id(UUID.randomUUID().toString()).build();
    JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers);
    JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
    JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> {
        try {
            return JWS_SIGNER_FACTORY.createJWSSigner(key);
        } catch (JOSEException ex) {
            throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex);
        }
    });
    SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
    try {
        signedJwt.sign(jwsSigner);
    } catch (JOSEException ex) {
        throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
    }
    String jws = signedJwt.serialize();
    return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Jwt(org.springframework.security.oauth2.jwt.Jwt) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 34 with JWK

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

the class WebClientReactiveClientCredentialsTokenResponseClientTests method getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent.

@Test
public void getTokenResponseWhenAuthenticationPrivateKeyJwtThenFormParametersAreSent() throws Exception {
    // @formatter:off
    enqueueJson("{\n" + "	  \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}");
    // @formatter:on
    // @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);
    OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
    this.client.getTokenResponse(request).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials", "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) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) WebClient(org.springframework.web.reactive.function.client.WebClient) 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) 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) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) BodyExtractor(org.springframework.web.reactive.function.BodyExtractor) 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.validateMockitoUsage(org.mockito.Mockito.validateMockitoUsage) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) URLEncoder(java.net.URLEncoder) Base64(java.util.Base64) AfterEach(org.junit.jupiter.api.AfterEach) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) MockResponse(okhttp3.mockwebserver.MockResponse) Collections(java.util.Collections) 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)

Example 35 with JWK

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

the class WebClientReactivePasswordTokenResponseClientTests 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);
    OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
    this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block();
    RecordedRequest actualRequest = this.server.takeRequest();
    assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
    assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=password", "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) 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) Collections(java.util.Collections) 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)

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