Search in sources :

Example 1 with AuthorizationResponseToken

use of org.keycloak.representations.AuthorizationResponseToken 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 AuthorizationResponseToken

use of org.keycloak.representations.AuthorizationResponseToken in project keycloak by keycloak.

the class AuthorizationTokenResponseModeTest method authorizationRequestFormPostJWTResponseMode.

@Test
public void authorizationRequestFormPostJWTResponseMode() throws IOException {
    oauth.responseMode(OIDCResponseMode.FORM_POST_JWT.value());
    oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
    oauth.doLoginGrant("test-user@localhost", "password");
    String sources = driver.getPageSource();
    System.out.println(sources);
    String responseTokenEncoded = driver.findElement(By.id("response")).getText();
    AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(responseTokenEncoded);
    assertEquals("test-app", responseToken.getAudience()[0]);
    Assert.assertNotNull(responseToken.getOtherClaims().get("code"));
    assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state"));
    Assert.assertNull(responseToken.getOtherClaims().get("error"));
    String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID);
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 3 with AuthorizationResponseToken

use of org.keycloak.representations.AuthorizationResponseToken in project keycloak by keycloak.

the class AuthorizationTokenResponseModeTest method authorizationRequestJWTResponseModeAccessTokenResponseType.

@Test
public void authorizationRequestJWTResponseModeAccessTokenResponseType() throws Exception {
    ClientManager.realm(adminClient.realm("test")).clientId("test-app").implicitFlow(true);
    // jwt response_mode. It should fallback to fragment.jwt when its hybrid flow
    oauth.responseMode("jwt");
    oauth.responseType("token id_token");
    oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
    oauth.nonce("123456");
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
    assertTrue(response.isRedirected());
    AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse());
    assertEquals("test-app", responseToken.getAudience()[0]);
    Assert.assertNull(responseToken.getOtherClaims().get("code"));
    assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state"));
    Assert.assertNull(responseToken.getOtherClaims().get("error"));
    Assert.assertNotNull(responseToken.getOtherClaims().get("id_token"));
    String idTokenEncoded = (String) responseToken.getOtherClaims().get("id_token");
    IDToken idToken = oauth.verifyIDToken(idTokenEncoded);
    assertEquals("123456", idToken.getNonce());
    Assert.assertNotNull(responseToken.getOtherClaims().get("access_token"));
    String accessTokenEncoded = (String) responseToken.getOtherClaims().get("access_token");
    AccessToken accessToken = oauth.verifyToken(accessTokenEncoded);
    assertEquals("123456", accessToken.getNonce());
    URI currentUri = new URI(driver.getCurrentUrl());
    Assert.assertNull(currentUri.getRawQuery());
    Assert.assertNotNull(currentUri.getRawFragment());
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) IDToken(org.keycloak.representations.IDToken) URI(java.net.URI) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 4 with AuthorizationResponseToken

use of org.keycloak.representations.AuthorizationResponseToken in project keycloak by keycloak.

the class ClientPoliciesTest method testSecureResponseTypeExecutor.

@Test
public void testSecureResponseTypeExecutor() throws Exception {
    // register profiles
    String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
    updateProfiles(json);
    // register policies
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "A Primeira Politica", Boolean.TRUE).addCondition(ClientRolesConditionFactory.PROVIDER_ID, createClientRolesConditionConfig(Arrays.asList(SAMPLE_CLIENT_ROLE))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    String clientId = generateSuffixedName(CLIENT_NAME);
    String clientSecret = "secret";
    String cid = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
        clientRep.setSecret(clientSecret);
        clientRep.setStandardFlowEnabled(Boolean.TRUE);
        clientRep.setImplicitFlowEnabled(Boolean.TRUE);
        clientRep.setPublicClient(Boolean.FALSE);
    });
    adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(SAMPLE_CLIENT_ROLE).build());
    oauth.clientId(clientId);
    oauth.openLoginForm();
    assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
    assertEquals("invalid response_type", oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
    oauth.nonce("vbwe566fsfffds");
    oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
    oauth.doLogout(res.getRefreshToken(), clientSecret);
    events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
    // update profiles
    json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.TRUE)).toRepresentation()).toString();
    updateProfiles(json);
    // token response type allowed
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
    oauth.nonce("cie8cjcwiw");
    oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    loginEvent = events.expectLogin().client(clientId).assertEvent();
    sessionId = loginEvent.getSessionId();
    codeId = loginEvent.getDetails().get(Details.CODE_ID);
    code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
    oauth.doLogout(res.getRefreshToken(), clientSecret);
    events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
    // shall allow code using response_mode jwt
    oauth.responseType(OIDCResponseType.CODE);
    oauth.responseMode("jwt");
    OAuthClient.AuthorizationEndpointResponse authzResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    String jwsResponse = authzResponse.getResponse();
    AuthorizationResponseToken responseObject = oauth.verifyAuthorizationResponseToken(jwsResponse);
    code = (String) responseObject.getOtherClaims().get(OAuth2Constants.CODE);
    res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    // update profiles
    json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.FALSE)).toRepresentation()).toString();
    updateProfiles(json);
    oauth.openLogout();
    // token response type allowed
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
    oauth.responseMode("jwt");
    oauth.openLoginForm();
    final JWSInput errorJws = new JWSInput(new OAuthClient.AuthorizationEndpointResponse(oauth).getResponse());
    JsonNode errorClaims = JsonSerialization.readValue(errorJws.getContent(), JsonNode.class);
    assertEquals(OAuthErrorException.INVALID_REQUEST, errorClaims.get("error").asText());
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientProfilesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder) ClientPoliciesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientPolicyBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder) JsonNode(com.fasterxml.jackson.databind.JsonNode) JWSInput(org.keycloak.jose.jws.JWSInput) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) Test(org.junit.Test)

Example 5 with AuthorizationResponseToken

use of org.keycloak.representations.AuthorizationResponseToken in project keycloak by keycloak.

the class AuthorizationTokenResponseModeTest method authorizationRequestQueryJWTResponseMode.

@Test
public void authorizationRequestQueryJWTResponseMode() throws Exception {
    oauth.responseMode(OIDCResponseMode.QUERY_JWT.value());
    oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
    assertTrue(response.isRedirected());
    AuthorizationResponseToken responseToken = oauth.verifyAuthorizationResponseToken(response.getResponse());
    assertEquals("test-app", responseToken.getAudience()[0]);
    Assert.assertNotNull(responseToken.getOtherClaims().get("code"));
    assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", responseToken.getOtherClaims().get("state"));
    Assert.assertNull(responseToken.getOtherClaims().get("error"));
    String codeId = events.expectLogin().assertEvent().getDetails().get(Details.CODE_ID);
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

AuthorizationResponseToken (org.keycloak.representations.AuthorizationResponseToken)10 Test (org.junit.Test)9 OAuthClient (org.keycloak.testsuite.util.OAuthClient)9 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 URI (java.net.URI)4 UriBuilder (javax.ws.rs.core.UriBuilder)2 IDToken (org.keycloak.representations.IDToken)2 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 PrivateKey (java.security.PrivateKey)1 ClientResource (org.keycloak.admin.client.resource.ClientResource)1 JWEException (org.keycloak.jose.jwe.JWEException)1 JWEHeader (org.keycloak.jose.jwe.JWEHeader)1 JWEAlgorithmProvider (org.keycloak.jose.jwe.alg.JWEAlgorithmProvider)1 JWEEncryptionProvider (org.keycloak.jose.jwe.enc.JWEEncryptionProvider)1 JWSInput (org.keycloak.jose.jws.JWSInput)1 AccessToken (org.keycloak.representations.AccessToken)1 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)1 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)1