Search in sources :

Example 1 with JWEHeader

use of org.keycloak.jose.jwe.JWEHeader in project keycloak by keycloak.

the class AuthorizationTokenEncryptionTest method testAuthorizationTokenSignatureAndEncryption.

private void testAuthorizationTokenSignatureAndEncryption(String sigAlgorithm, String algAlgorithm, String encAlgorithm) {
    ClientResource clientResource;
    ClientRepresentation clientRep;
    try {
        // generate and register encryption key onto client
        TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
        oidcClientEndpointsResource.generateKeys(algAlgorithm);
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // set authorization response signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationSignedResponseAlg(sigAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseAlg(algAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseEnc(encAlgorithm);
        // use and set jwks_url
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
        String jwksUrl = TestApplicationResourceUrls.clientJwksUri();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(jwksUrl);
        clientResource.update(clientRep);
        // get authorization response
        oauth.responseMode("jwt");
        oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
        OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
        // parse JWE and JOSE Header
        String jweStr = response.getResponse();
        String[] parts = jweStr.split("\\.");
        Assert.assertEquals(parts.length, 5);
        // get decryption key
        // not publickey , use privateKey
        Map<String, String> keyPair = oidcClientEndpointsResource.getKeysAsPem();
        PrivateKey decryptionKEK = PemUtils.decodePrivateKey(keyPair.get("privateKey"));
        // verify and decrypt JWE
        JWEAlgorithmProvider algorithmProvider = getJweAlgorithmProvider(algAlgorithm);
        JWEEncryptionProvider encryptionProvider = getJweEncryptionProvider(encAlgorithm);
        byte[] decodedString = TokenUtil.jweKeyEncryptionVerifyAndDecode(decryptionKEK, jweStr, algorithmProvider, encryptionProvider);
        String authorizationTokenString = new String(decodedString, "UTF-8");
        // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field
        JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]);
        Assert.assertEquals("JWT", jweHeader.getContentType());
        // verify JWS
        AuthorizationResponseToken authorizationToken = oauth.verifyAuthorizationResponseToken(authorizationTokenString);
        Assert.assertEquals("test-app", authorizationToken.getAudience()[0]);
        Assert.assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", authorizationToken.getOtherClaims().get("state"));
        Assert.assertNotNull(authorizationToken.getOtherClaims().get("code"));
    } catch (JWEException | UnsupportedEncodingException e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // revert id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationSignedResponseAlg(Algorithm.RS256);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseAlg(null);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseEnc(null);
        // revert jwks_url settings
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(false);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(null);
        clientResource.update(clientRep);
    }
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) PrivateKey(java.security.PrivateKey) TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JWEHeader(org.keycloak.jose.jwe.JWEHeader) ClientResource(org.keycloak.admin.client.resource.ClientResource)

Example 2 with JWEHeader

use of org.keycloak.jose.jwe.JWEHeader in project keycloak by keycloak.

the class IdTokenEncryptionTest method testIdTokenSignatureAndEncryption.

private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAlgorithm, String encAlgorithm) {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        // generate and register encryption key onto client
        TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
        oidcClientEndpointsResource.generateKeys(algAlgorithm);
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // set id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(sigAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(algAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(encAlgorithm);
        // use and set jwks_url
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
        String jwksUrl = TestApplicationResourceUrls.clientJwksUri();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(jwksUrl);
        clientResource.update(clientRep);
        // get id token
        OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
        String code = response.getCode();
        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
        // parse JWE and JOSE Header
        String jweStr = tokenResponse.getIdToken();
        String[] parts = jweStr.split("\\.");
        Assert.assertEquals(parts.length, 5);
        // get decryption key
        // not publickey , use privateKey
        Map<String, String> keyPair = oidcClientEndpointsResource.getKeysAsPem();
        PrivateKey decryptionKEK = PemUtils.decodePrivateKey(keyPair.get("privateKey"));
        // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field
        JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]);
        Assert.assertEquals("JWT", jweHeader.getContentType());
        // verify and decrypt JWE
        JWEAlgorithmProvider algorithmProvider = getJweAlgorithmProvider(algAlgorithm);
        JWEEncryptionProvider encryptionProvider = getJweEncryptionProvider(encAlgorithm);
        byte[] decodedString = TokenUtil.jweKeyEncryptionVerifyAndDecode(decryptionKEK, jweStr, algorithmProvider, encryptionProvider);
        String idTokenString = new String(decodedString, "UTF-8");
        // verify JWS
        IDToken idToken = oauth.verifyIDToken(idTokenString);
        Assert.assertEquals("test-user@localhost", idToken.getPreferredUsername());
        Assert.assertEquals("test-app", idToken.getIssuedFor());
    } catch (JWEException | UnsupportedEncodingException e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // revert id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(Algorithm.RS256);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(null);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(null);
        // revert jwks_url settings
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(false);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(null);
        clientResource.update(clientRep);
    }
}
Also used : PrivateKey(java.security.PrivateKey) TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JWEHeader(org.keycloak.jose.jwe.JWEHeader) AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken)

Example 3 with JWEHeader

use of org.keycloak.jose.jwe.JWEHeader in project keycloak by keycloak.

the class OIDCAdvancedRequestParamsTest method testRealmPublicKeyEncryptedRequestObjectUsingKid.

@Test
public void testRealmPublicKeyEncryptedRequestObjectUsingKid() throws Exception {
    KeysMetadataRepresentation.KeyMetadataRepresentation encKey = KeyUtils.getActiveEncKey(testRealm().keys().getKeyMetadata(), org.keycloak.crypto.Algorithm.RS256);
    JWEHeader jweHeader = new JWEHeader(RSA_OAEP, JWEConstants.A128CBC_HS256, null, encKey.getKid());
    assertRequestObjectEncryption(jweHeader);
}
Also used : KeysMetadataRepresentation(org.keycloak.representations.idm.KeysMetadataRepresentation) JWEHeader(org.keycloak.jose.jwe.JWEHeader) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 4 with JWEHeader

use of org.keycloak.jose.jwe.JWEHeader in project keycloak by keycloak.

the class TokenUtil method jweDirectEncode.

public static String jweDirectEncode(Key aesKey, Key hmacKey, byte[] contentBytes) throws JWEException {
    int keyLength = aesKey.getEncoded().length;
    String encAlgorithm;
    switch(keyLength) {
        case 16:
            encAlgorithm = JWEConstants.A128CBC_HS256;
            break;
        case 24:
            encAlgorithm = JWEConstants.A192CBC_HS384;
            break;
        case 32:
            encAlgorithm = JWEConstants.A256CBC_HS512;
            break;
        default:
            throw new IllegalArgumentException("Bad size for Encryption key: " + aesKey + ". Valid sizes are 16, 24, 32.");
    }
    JWEHeader jweHeader = new JWEHeader(JWEConstants.DIR, encAlgorithm, null);
    JWE jwe = new JWE().header(jweHeader).content(contentBytes);
    jwe.getKeyStorage().setCEKKey(aesKey, JWEKeyStorage.KeyUse.ENCRYPTION).setCEKKey(hmacKey, JWEKeyStorage.KeyUse.SIGNATURE);
    return jwe.encodeJwe();
}
Also used : JWEHeader(org.keycloak.jose.jwe.JWEHeader) JWE(org.keycloak.jose.jwe.JWE)

Example 5 with JWEHeader

use of org.keycloak.jose.jwe.JWEHeader in project keycloak by keycloak.

the class OIDCAdvancedRequestParamsTest method createEncryptedRequestObject.

private String createEncryptedRequestObject(String encAlg) throws IOException, JWEException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        OIDCConfigurationRepresentation representation = SimpleHttp.doGet(getAuthServerRoot().toString() + "realms/" + oauth.getRealm() + "/.well-known/openid-configuration", httpClient).asJson(OIDCConfigurationRepresentation.class);
        String jwksUri = representation.getJwksUri();
        JSONWebKeySet jsonWebKeySet = SimpleHttp.doGet(jwksUri, httpClient).asJson(JSONWebKeySet.class);
        Map<String, PublicKey> keysForUse = JWKSUtils.getKeysForUse(jsonWebKeySet, JWK.Use.ENCRYPTION);
        String keyId = null;
        if (keyId == null) {
            KeysMetadataRepresentation.KeyMetadataRepresentation encKey = KeyUtils.getActiveEncKey(testRealm().keys().getKeyMetadata(), org.keycloak.crypto.Algorithm.PS256);
            keyId = encKey.getKid();
        }
        PublicKey decryptionKEK = keysForUse.get(keyId);
        JWE jwe = new JWE().header(new JWEHeader(encAlg, JWEConstants.A256GCM, null)).content(createAndSignRequestObject().getBytes());
        jwe.getKeyStorage().setEncryptionKey(decryptionKEK);
        return jwe.encodeJwe();
    }
}
Also used : KeysMetadataRepresentation(org.keycloak.representations.idm.KeysMetadataRepresentation) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) JWEHeader(org.keycloak.jose.jwe.JWEHeader) JSONWebKeySet(org.keycloak.jose.jwk.JSONWebKeySet) PublicKey(java.security.PublicKey) JWE(org.keycloak.jose.jwe.JWE) OIDCConfigurationRepresentation(org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)

Aggregations

JWEHeader (org.keycloak.jose.jwe.JWEHeader)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 PrivateKey (java.security.PrivateKey)2 ClientResource (org.keycloak.admin.client.resource.ClientResource)2 JWE (org.keycloak.jose.jwe.JWE)2 JWEException (org.keycloak.jose.jwe.JWEException)2 JWEAlgorithmProvider (org.keycloak.jose.jwe.alg.JWEAlgorithmProvider)2 JWEEncryptionProvider (org.keycloak.jose.jwe.enc.JWEEncryptionProvider)2 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)2 KeysMetadataRepresentation (org.keycloak.representations.idm.KeysMetadataRepresentation)2 TestOIDCEndpointsApplicationResource (org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource)2 OAuthClient (org.keycloak.testsuite.util.OAuthClient)2 PublicKey (java.security.PublicKey)1 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)1 Test (org.junit.Test)1 JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)1 OIDCConfigurationRepresentation (org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation)1 AuthorizationResponseToken (org.keycloak.representations.AuthorizationResponseToken)1 IDToken (org.keycloak.representations.IDToken)1 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)1