Search in sources :

Example 91 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation 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 92 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class ClientPoliciesTest method testSecureSigningAlgorithmForSignedJwtEnforceExecutorWithNotSecureAlg.

@Test
public void testSecureSigningAlgorithmForSignedJwtEnforceExecutorWithNotSecureAlg() throws Exception {
    // register profiles
    String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "Ensimmainen Profiili").addExecutor(SecureSigningAlgorithmForSignedJwtExecutorFactory.PROVIDER_ID, createSecureSigningAlgorithmForSignedJwtEnforceExecutorConfig(Boolean.FALSE)).toRepresentation()).toString();
    updateProfiles(json);
    // register policies
    String roleAlphaName = "sample-client-role-alpha";
    String roleZetaName = "sample-client-role-zeta";
    String roleCommonName = "sample-client-role-common";
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "Den Forste Politikken", Boolean.TRUE).addCondition(ClientRolesConditionFactory.PROVIDER_ID, createClientRolesConditionConfig(Arrays.asList(roleAlphaName, roleZetaName))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    // create a client with client role
    String clientId = generateSuffixedName(CLIENT_NAME);
    String cid = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
        clientRep.setSecret("secret");
        clientRep.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID);
        clientRep.setAttributes(new HashMap<>());
        clientRep.getAttributes().put(OIDCConfigAttributes.TOKEN_ENDPOINT_AUTH_SIGNING_ALG, org.keycloak.crypto.Algorithm.RS256);
    });
    adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(roleAlphaName).build());
    adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(roleCommonName).build());
    ClientResource clientResource = ApiUtil.findClientByClientId(adminClient.realm(REALM_NAME), clientId);
    ClientRepresentation clientRep = clientResource.toRepresentation();
    KeyPair keyPair = setupJwksUrl(org.keycloak.crypto.Algorithm.RS256, clientRep, clientResource);
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    String signedJwt = createSignedRequestToken(clientId, privateKey, publicKey, org.keycloak.crypto.Algorithm.RS256);
    oauth.clientId(clientId);
    oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
    String sessionId = loginEvent.getSessionId();
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    // obtain access token
    OAuthClient.AccessTokenResponse response = doAccessTokenRequestWithSignedJWT(code, signedJwt);
    assertEquals(400, response.getStatusCode());
    assertEquals(OAuthErrorException.INVALID_GRANT, response.getError());
    assertEquals("not allowed signature algorithm.", response.getErrorDescription());
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) OAuthClient(org.keycloak.testsuite.util.OAuthClient) PublicKey(java.security.PublicKey) 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) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) ClientResource(org.keycloak.admin.client.resource.ClientResource) Test(org.junit.Test)

Example 93 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class ClientPoliciesTest method failTokenRequestByNotFollowingPKCE.

private void failTokenRequestByNotFollowingPKCE(String clientId, String clientSecret) {
    oauth.clientId(clientId);
    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 = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(OAuthErrorException.INVALID_GRANT, res.getError());
    assertEquals("PKCE code verifier not specified", res.getErrorDescription());
    events.expect(EventType.CODE_TO_TOKEN_ERROR).client(clientId).session(sessionId).clearDetails().error(Errors.CODE_VERIFIER_MISSING).assertEvent();
    oauth.openLogout();
    events.expectLogout(sessionId).clearDetails().assertEvent();
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation)

Example 94 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class CIBATest method testMultipleClientsBackchannelAuthenticationFlows.

@Test
public void testMultipleClientsBackchannelAuthenticationFlows() throws Exception {
    ClientResource firstClientResource = null;
    ClientResource secondClientResource = null;
    ClientRepresentation firstClientRep = null;
    ClientRepresentation secondClientRep = null;
    try {
        final String username = "nutzername-gelb";
        // see testrealm.json
        final String firstClientName = "test-app-scope";
        final String secondClientName = TEST_CLIENT_NAME;
        final String firstClientPassword = "password";
        final String secondClientPassword = TEST_CLIENT_PASSWORD;
        String firstClientAuthReqId = null;
        String secondClientAuthReqId = null;
        firstClientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), firstClientName);
        assertThat(firstClientResource, notNullValue());
        firstClientRep = firstClientResource.toRepresentation();
        prepareCIBASettings(firstClientResource, firstClientRep);
        secondClientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), secondClientName);
        assertThat(secondClientResource, notNullValue());
        secondClientRep = secondClientResource.toRepresentation();
        prepareCIBASettings(secondClientResource, secondClientRep);
        // first client Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(firstClientName, firstClientPassword, username, "asdfghjkl");
        firstClientAuthReqId = response.getAuthReqId();
        // first client Authentication Channel Request
        TestAuthenticationChannelRequest firstClientAuthenticationChannelReq = doAuthenticationChannelRequest("asdfghjkl");
        // first client Authentication Channel completed
        EventRepresentation firstClientloginEvent = doAuthenticationChannelCallback(firstClientAuthenticationChannelReq);
        // second client Backchannel Authentication Request
        response = doBackchannelAuthenticationRequest(secondClientName, secondClientPassword, username, "qwertyui");
        secondClientAuthReqId = response.getAuthReqId();
        // second client Authentication Channel Request
        TestAuthenticationChannelRequest secondClientAuthenticationChannelReq = doAuthenticationChannelRequest("qwertyui");
        // second client Authentication Channel completed
        EventRepresentation secondClientloginEvent = doAuthenticationChannelCallback(secondClientAuthenticationChannelReq);
        // second client Token Request
        OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequest(secondClientName, secondClientPassword, username, secondClientAuthReqId);
        // first client Token Request
        tokenRes = doBackchannelAuthenticationTokenRequest(firstClientName, firstClientPassword, username, firstClientAuthReqId);
    } finally {
        revertCIBASettings(firstClientResource, firstClientRep);
        revertCIBASettings(secondClientResource, secondClientRep);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 95 with EventRepresentation

use of org.keycloak.representations.idm.EventRepresentation in project keycloak by keycloak.

the class CIBATest method testBackchannelAuthenticationFlowWithSignedAuthenticationRequest.

private void testBackchannelAuthenticationFlowWithSignedAuthenticationRequest(boolean useRequestUri, String sigAlg) throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        final String username = "nutzername-rot";
        final String bindingMessage = "BASTION";
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep);
        AuthorizationEndpointRequestObject sharedAuthenticationRequest = createValidSharedAuthenticationRequest();
        sharedAuthenticationRequest.setLoginHint(username);
        sharedAuthenticationRequest.setBindingMessage(bindingMessage);
        registerSharedAuthenticationRequest(sharedAuthenticationRequest, TEST_CLIENT_NAME, sigAlg, useRequestUri);
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, null, null);
        // user Authentication Channel Request
        TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
        AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
        Assert.assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
        Assert.assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
        // user Authentication Channel completed
        EventRepresentation loginEvent = doAuthenticationChannelCallback(testRequest);
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String userId = loginEvent.getUserId();
        // user Token Request
        OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
        // token introspection
        String tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // token refresh
        tokenRes = doRefreshTokenRequest(tokenRes.getRefreshToken(), username, sessionId, false);
        // token introspection after token refresh
        tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // logout by refresh token
        EventRepresentation logoutEvent = doLogoutByRefreshToken(tokenRes.getRefreshToken(), sessionId, userId, false);
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AuthorizationEndpointRequestObject(org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource.AuthorizationEndpointRequestObject) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Aggregations

EventRepresentation (org.keycloak.representations.idm.EventRepresentation)164 Test (org.junit.Test)124 OAuthClient (org.keycloak.testsuite.util.OAuthClient)93 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)60 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)44 RefreshToken (org.keycloak.representations.RefreshToken)27 ClientResource (org.keycloak.admin.client.resource.ClientResource)26 AccessToken (org.keycloak.representations.AccessToken)26 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)25 IDToken (org.keycloak.representations.IDToken)23 Matchers.containsString (org.hamcrest.Matchers.containsString)15 AbstractAdminTest (org.keycloak.testsuite.admin.AbstractAdminTest)15 Response (javax.ws.rs.core.Response)13 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)13 AccessTokenResponse (org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse)12 IOException (java.io.IOException)11 RealmResource (org.keycloak.admin.client.resource.RealmResource)11 AssertEvents (org.keycloak.testsuite.AssertEvents)10 JWSInput (org.keycloak.jose.jws.JWSInput)9 TestAuthenticationChannelRequest (org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest)9