Search in sources :

Example 6 with TestOIDCEndpointsApplicationResource

use of org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource in project keycloak by keycloak.

the class OIDCJwksClientRegistrationTest method createClientWithJWKSURI_rotateClientKeys.

@Test
public void createClientWithJWKSURI_rotateClientKeys() throws Exception {
    OIDCClientRepresentation clientRep = createRep();
    clientRep.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS));
    clientRep.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT);
    // Generate keys for client
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    Map<String, String> generatedKeys = oidcClientEndpointsResource.generateKeys("RS256");
    clientRep.setJwksUri(TestApplicationResourceUrls.clientJwksUri());
    OIDCClientRepresentation response = reg.oidc().create(clientRep);
    Assert.assertEquals(OIDCLoginProtocol.PRIVATE_KEY_JWT, response.getTokenEndpointAuthMethod());
    Assert.assertNull(response.getClientSecret());
    Assert.assertNull(response.getClientSecretExpiresAt());
    Assert.assertEquals(response.getJwksUri(), TestApplicationResourceUrls.clientJwksUri());
    // Tries to authenticate client with privateKey JWT
    assertAuthenticateClientSuccess(generatedKeys, response, KEEP_GENERATED_KID);
    // Add new key to the jwks
    Map<String, String> generatedKeys2 = oidcClientEndpointsResource.generateKeys("RS256");
    // Error should happen. KeyStorageProvider won't yet download new keys because of timeout
    assertAuthenticateClientError(generatedKeys2, response, KEEP_GENERATED_KID);
    setTimeOffset(20);
    // Now new keys should be successfully downloaded
    assertAuthenticateClientSuccess(generatedKeys2, response, KEEP_GENERATED_KID);
}
Also used : TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) Test(org.junit.Test)

Example 7 with TestOIDCEndpointsApplicationResource

use of org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource in project keycloak by keycloak.

the class ParTest method testSuccessfulUsingRequestParameter.

@Test
public void testSuccessfulUsingRequestParameter() throws Exception {
    try {
        // setup PAR realm settings
        int requestUriLifespan = 45;
        setParRealmSettings(requestUriLifespan);
        // create client dynamically
        String clientId = createClientDynamically(generateSuffixedName(CLIENT_NAME), (OIDCClientRepresentation clientRep) -> {
            clientRep.setRequirePushedAuthorizationRequests(Boolean.TRUE);
            clientRep.setRedirectUris(new ArrayList<>(Arrays.asList(CLIENT_REDIRECT_URI)));
        });
        oauth.clientId(clientId);
        OIDCClientRepresentation oidcCRep = getClientDynamically(clientId);
        String clientSecret = oidcCRep.getClientSecret();
        assertEquals(Boolean.TRUE, oidcCRep.getRequirePushedAuthorizationRequests());
        assertTrue(oidcCRep.getRedirectUris().contains(CLIENT_REDIRECT_URI));
        assertEquals(OIDCLoginProtocol.CLIENT_SECRET_BASIC, oidcCRep.getTokenEndpointAuthMethod());
        TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject requestObject = new TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject();
        requestObject.id(KeycloakModelUtils.generateId());
        requestObject.iat(Long.valueOf(Time.currentTime()));
        requestObject.exp(requestObject.getIat() + Long.valueOf(300));
        requestObject.nbf(requestObject.getIat());
        requestObject.setClientId(oauth.getClientId());
        requestObject.setResponseType("code");
        requestObject.setRedirectUriParam(CLIENT_REDIRECT_URI);
        requestObject.setScope("openid");
        requestObject.setNonce(KeycloakModelUtils.generateId());
        byte[] contentBytes = JsonSerialization.writeValueAsBytes(requestObject);
        String encodedRequestObject = Base64Url.encode(contentBytes);
        TestOIDCEndpointsApplicationResource client = testingClient.testApp().oidcClientEndpoints();
        // use and set jwks_url
        ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm(oauth.getRealm()), oauth.getClientId());
        ClientRepresentation clientRep = clientResource.toRepresentation();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(TestApplicationResourceUrls.clientJwksUri());
        clientResource.update(clientRep);
        client.generateKeys(org.keycloak.crypto.Algorithm.RS256);
        client.registerOIDCRequest(encodedRequestObject, org.keycloak.crypto.Algorithm.RS256);
        // do not send any other parameter but the request request parameter
        oauth.request(client.getOIDCRequest());
        oauth.responseType(null);
        oauth.redirectUri(null);
        oauth.scope(null);
        ParResponse pResp = oauth.doPushedAuthorizationRequest(clientId, clientSecret);
        assertEquals(201, pResp.getStatusCode());
        String requestUri = pResp.getRequestUri();
        assertEquals(requestUriLifespan, pResp.getExpiresIn());
        // Authorization Request with request_uri of PAR
        // remove parameters as query strings of uri
        oauth.redirectUri(null);
        oauth.scope(null);
        oauth.responseType(null);
        oauth.request(null);
        oauth.requestUri(requestUri);
        OAuthClient.AuthorizationEndpointResponse loginResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
        // Token Request
        // get tokens, it needed. https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3
        oauth.redirectUri(CLIENT_REDIRECT_URI);
        OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(loginResponse.getCode(), clientSecret);
        assertEquals(200, res.getStatusCode());
        oauth.verifyToken(res.getAccessToken());
        IDToken idToken = oauth.verifyIDToken(res.getIdToken());
        assertEquals(requestObject.getNonce(), idToken.getNonce());
    } finally {
        restoreParRealmSettings();
    }
}
Also used : TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OAuthClient(org.keycloak.testsuite.util.OAuthClient) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ParResponse(org.keycloak.testsuite.util.OAuthClient.ParResponse) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken) TestingOIDCEndpointsApplicationResource(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource) AbstractClientPoliciesTest(org.keycloak.testsuite.client.AbstractClientPoliciesTest) Test(org.junit.Test)

Example 8 with TestOIDCEndpointsApplicationResource

use of org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource in project keycloak by keycloak.

the class AuthorizationTokenEncryptionTest method testAuthorizationEncryptionWithoutEncryptionKEK.

@Test
@UncaughtServerErrorExpected
public void testAuthorizationEncryptionWithoutEncryptionKEK() throws MalformedURLException, URISyntaxException {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        // generate and register signing/verifying key onto client, not encryption key
        TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
        oidcClientEndpointsResource.generateKeys(Algorithm.RS256);
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // set id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationSignedResponseAlg(Algorithm.RS256);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseAlg(JWEConstants.RSA1_5);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseEnc(JWEConstants.A128CBC_HS256);
        // 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 but failed
        oauth.responseMode("jwt");
        oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
        OAuthClient.AuthorizationEndpointResponse errorResponse = oauth.doLogin("test-user@localhost", "password");
        System.out.println(driver.getPageSource().contains("Unexpected error when handling authentication request to identity provider."));
    } finally {
        // Revert
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        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 : TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 9 with TestOIDCEndpointsApplicationResource

use of org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource 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 10 with TestOIDCEndpointsApplicationResource

use of org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource 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)

Aggregations

TestOIDCEndpointsApplicationResource (org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource)48 Test (org.junit.Test)33 ClientResource (org.keycloak.admin.client.resource.ClientResource)28 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)27 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)22 OAuthClient (org.keycloak.testsuite.util.OAuthClient)21 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)14 AbstractAdminTest (org.keycloak.testsuite.admin.AbstractAdminTest)13 KeyPair (java.security.KeyPair)6 ArrayList (java.util.ArrayList)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 TestingOIDCEndpointsApplicationResource (org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource)6 PrivateKey (java.security.PrivateKey)5 TestAuthenticationChannelRequest (org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest)5 JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)4 IDToken (org.keycloak.representations.IDToken)4 AbstractClientPoliciesTest (org.keycloak.testsuite.client.AbstractClientPoliciesTest)4 ParResponse (org.keycloak.testsuite.util.OAuthClient.ParResponse)4 PublicKey (java.security.PublicKey)3 AuthenticationRequestAcknowledgement (org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement)3