Search in sources :

Example 1 with ClientScopeResource

use of org.keycloak.admin.client.resource.ClientScopeResource in project keycloak by keycloak.

the class OIDCProtocolMappersTest method testUserRolesMovedFromAccessTokenProperties.

// Test to update protocolMappers to not have roles on the default position (realm_access and resource_access properties)
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testUserRolesMovedFromAccessTokenProperties() throws Exception {
    RealmResource realm = adminClient.realm("test");
    ClientScopeResource rolesScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE);
    // Update builtin protocolMappers to put roles to different position (claim "custom.roles") for both realm and client roles
    ProtocolMapperRepresentation realmRolesMapper = null;
    ProtocolMapperRepresentation clientRolesMapper = null;
    for (ProtocolMapperRepresentation rep : rolesScope.getProtocolMappers().getMappers()) {
        if (OIDCLoginProtocolFactory.REALM_ROLES.equals(rep.getName())) {
            realmRolesMapper = rep;
        } else if (OIDCLoginProtocolFactory.CLIENT_ROLES.equals(rep.getName())) {
            clientRolesMapper = rep;
        }
    }
    String realmRolesTokenClaimOrig = realmRolesMapper.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME);
    String clientRolesTokenClaimOrig = clientRolesMapper.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME);
    realmRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "custom.roles");
    rolesScope.getProtocolMappers().update(realmRolesMapper.getId(), realmRolesMapper);
    clientRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "custom.roles");
    rolesScope.getProtocolMappers().update(clientRolesMapper.getId(), clientRolesMapper);
    // Create some hardcoded role mapper
    Response resp = rolesScope.getProtocolMappers().createMapper(createHardcodedRole("hard-realm", "hardcoded"));
    String hardcodedMapperId = ApiUtil.getCreatedId(resp);
    resp.close();
    try {
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");
        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
        // Assert roles are not on their original positions
        Assert.assertNull(accessToken.getRealmAccess());
        Assert.assertTrue(accessToken.getResourceAccess().isEmpty());
        // KEYCLOAK-8481 Assert that accessToken JSON doesn't have "realm_access" or "resource_access" fields in it
        String accessTokenJson = new String(new JWSInput(response.getAccessToken()).getContent(), StandardCharsets.UTF_8);
        Assert.assertFalse(accessTokenJson.contains("realm_access"));
        Assert.assertFalse(accessTokenJson.contains("resource_access"));
        // Assert both realm and client roles on the new position. Hardcoded role should be here as well
        Map<String, Object> cst1 = (Map<String, Object>) accessToken.getOtherClaims().get("custom");
        List<String> roles = (List<String>) cst1.get("roles");
        Assert.assertNames(roles, "offline_access", "user", "customer-user", "hardcoded", AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS);
        // Assert audience
        Assert.assertNames(Arrays.asList(accessToken.getAudience()), "account");
    } finally {
        // Revert
        rolesScope.getProtocolMappers().delete(hardcodedMapperId);
        realmRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, realmRolesTokenClaimOrig);
        rolesScope.getProtocolMappers().update(realmRolesMapper.getId(), realmRolesMapper);
        clientRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, clientRolesTokenClaimOrig);
        rolesScope.getProtocolMappers().update(clientRolesMapper.getId(), clientRolesMapper);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) JWSInput(org.keycloak.jose.jws.JWSInput) Response(javax.ws.rs.core.Response) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) AccessToken(org.keycloak.representations.AccessToken) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 2 with ClientScopeResource

use of org.keycloak.admin.client.resource.ClientScopeResource in project keycloak by keycloak.

the class AccessTokenTest method testClientScope.

@Test
public void testClientScope() throws Exception {
    RealmResource realm = adminClient.realm("test");
    RoleRepresentation realmRole = new RoleRepresentation();
    realmRole.setName("realm-test-role");
    realm.roles().create(realmRole);
    realmRole = realm.roles().get("realm-test-role").toRepresentation();
    RoleRepresentation realmRole2 = new RoleRepresentation();
    realmRole2.setName("realm-test-role2");
    realm.roles().create(realmRole2);
    realmRole2 = realm.roles().get("realm-test-role2").toRepresentation();
    List<UserRepresentation> users = realm.users().search("test-user@localhost", -1, -1);
    assertEquals(1, users.size());
    UserRepresentation user = users.get(0);
    List<RoleRepresentation> addRoles = new LinkedList<>();
    addRoles.add(realmRole);
    addRoles.add(realmRole2);
    realm.users().get(user.getId()).roles().realmLevel().add(addRoles);
    ClientScopeRepresentation rep = new ClientScopeRepresentation();
    rep.setName("scope");
    rep.setProtocol("openid-connect");
    Response response = realm.clientScopes().create(rep);
    assertEquals(201, response.getStatus());
    URI scopeUri = response.getLocation();
    String clientScopeId = ApiUtil.getCreatedId(response);
    response.close();
    ClientScopeResource clientScopeResource = adminClient.proxy(ClientScopeResource.class, scopeUri);
    ProtocolMapperModel hard = HardcodedClaim.create("hard", "hard", "coded", "String", true, true);
    ProtocolMapperRepresentation mapper = ModelToRepresentation.toRepresentation(hard);
    response = clientScopeResource.getProtocolMappers().createMapper(mapper);
    assertEquals(201, response.getStatus());
    response.close();
    ClientRepresentation clientRep = ApiUtil.findClientByClientId(realm, "test-app").toRepresentation();
    realm.clients().get(clientRep.getId()).addDefaultClientScope(clientScopeId);
    clientRep.setFullScopeAllowed(false);
    realm.clients().get(clientRep.getId()).update(clientRep);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        IDToken idToken = getIdToken(tokenResponse);
        assertEquals("coded", idToken.getOtherClaims().get("hard"));
        AccessToken accessToken = getAccessToken(tokenResponse);
        assertEquals("coded", accessToken.getOtherClaims().get("hard"));
        // check zero scope for client scope
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test that scope is added
    List<RoleRepresentation> addRole1 = new LinkedList<>();
    addRole1.add(realmRole);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole1);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        // check single role in scope for client scope
        assertNotNull(accessToken.getRealmAccess());
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test combined scopes
    List<RoleRepresentation> addRole2 = new LinkedList<>();
    addRole2.add(realmRole2);
    realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().add(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        // check zero scope for client scope
        assertNotNull(accessToken.getRealmAccess());
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        assertTrue(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // remove scopes and retest
    clientScopeResource.getScopeMappings().realmLevel().remove(addRole1);
    realm.clients().get(clientRep.getId()).getScopeMappings().realmLevel().remove(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        response.close();
        client.close();
    }
    // test don't use client scope scope. Add roles back to the clientScope, but they won't be available
    realm.clients().get(clientRep.getId()).removeDefaultClientScope(clientScopeId);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole1);
    clientScopeResource.getScopeMappings().realmLevel().add(addRole2);
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        AccessToken accessToken = getAccessToken(tokenResponse);
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole.getName()));
        Assert.assertFalse(accessToken.getRealmAccess().getRoles().contains(realmRole2.getName()));
        assertNull(accessToken.getOtherClaims().get("hard"));
        IDToken idToken = getIdToken(tokenResponse);
        assertNull(idToken.getOtherClaims().get("hard"));
        response.close();
        client.close();
    }
    // undo mappers
    realm.users().get(user.getId()).roles().realmLevel().remove(addRoles);
    realm.roles().get(realmRole.getName()).remove();
    realm.roles().get(realmRole2.getName()).remove();
    clientScopeResource.remove();
    {
        Client client = AdminClientUtil.createResteasyClient();
        UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT);
        URI grantUri = OIDCLoginProtocolService.tokenUrl(builder).build("test");
        WebTarget grantTarget = client.target(grantUri);
        response = executeGrantAccessTokenRequest(grantTarget);
        assertEquals(200, response.getStatus());
        org.keycloak.representations.AccessTokenResponse tokenResponse = response.readEntity(org.keycloak.representations.AccessTokenResponse.class);
        IDToken idToken = getIdToken(tokenResponse);
        assertNull(idToken.getOtherClaims().get("hard"));
        AccessToken accessToken = getAccessToken(tokenResponse);
        assertNull(accessToken.getOtherClaims().get("hard"));
        response.close();
        client.close();
    }
    events.clear();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) URI(java.net.URI) LinkedList(java.util.LinkedList) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Response(javax.ws.rs.core.Response) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) AccessToken(org.keycloak.representations.AccessToken) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) IDToken(org.keycloak.representations.IDToken) WebTarget(javax.ws.rs.client.WebTarget) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UriBuilder(javax.ws.rs.core.UriBuilder) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 3 with ClientScopeResource

use of org.keycloak.admin.client.resource.ClientScopeResource in project keycloak by keycloak.

the class OIDCScopeTest method testClientDisplayedOnConsentScreenWithEmptyConsentText.

// KEYCLOAK-7855
@Test
public void testClientDisplayedOnConsentScreenWithEmptyConsentText() throws Exception {
    // Add "displayOnConsentScreen" to client
    ClientResource thirdParty = ApiUtil.findClientByClientId(testRealm(), "third-party");
    ClientRepresentation thirdPartyRep = thirdParty.toRepresentation();
    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "true");
    thirdPartyRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, "");
    thirdParty.update(thirdPartyRep);
    // Change consent text on profile scope
    ClientScopeResource profileScope = ApiUtil.findClientScopeByName(testRealm(), OAuth2Constants.SCOPE_PROFILE);
    ClientScopeRepresentation profileScopeRep = profileScope.toRepresentation();
    profileScopeRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, " ");
    profileScope.update(profileScopeRep);
    // Login. ConsentTexts are empty for the client and for the "profile" scope, so it should fallback to name/clientId
    oauth.clientId("third-party");
    oauth.doLoginGrant("john", "password");
    grantPage.assertCurrent();
    grantPage.assertGrants("profile", OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT, "third-party");
    grantPage.accept();
    // Revert
    profileScopeRep.getAttributes().put(ClientScopeModel.CONSENT_SCREEN_TEXT, OIDCLoginProtocolFactory.PROFILE_SCOPE_CONSENT_TEXT);
    profileScope.update(profileScopeRep);
    thirdPartyRep.getAttributes().put(ClientScopeModel.DISPLAY_ON_CONSENT_SCREEN, "false");
    thirdParty.update(thirdPartyRep);
}
Also used : ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 4 with ClientScopeResource

use of org.keycloak.admin.client.resource.ClientScopeResource in project keycloak by keycloak.

the class OAuthGrantTest method oauthGrantOrderedClientScopes.

// KEYCLOAK-7470
@Test
public void oauthGrantOrderedClientScopes() throws Exception {
    // Add GUI Order to client scopes --- email=1, profile=2
    RealmResource appRealm = adminClient.realm(REALM_NAME);
    ClientScopeResource emailScope = ApiUtil.findClientScopeByName(appRealm, "email");
    ClientScopeRepresentation emailRep = emailScope.toRepresentation();
    emailRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "1");
    emailScope.update(emailRep);
    ClientScopeResource profileScope = ApiUtil.findClientScopeByName(appRealm, "profile");
    ClientScopeRepresentation profileRep = profileScope.toRepresentation();
    profileRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "2");
    profileScope.update(profileRep);
    // Display consent screen --- assert email, then profile
    oauth.clientId(THIRD_PARTY_APP);
    oauth.doLoginGrant("test-user@localhost", "password");
    grantPage.assertCurrent();
    List<String> displayedScopes = grantPage.getDisplayedGrants();
    Assert.assertEquals("Email address", displayedScopes.get(0));
    Assert.assertEquals("User profile", displayedScopes.get(1));
    grantPage.accept();
    // Display account mgmt --- assert email, then profile
    accountAppsPage.open();
    displayedScopes = accountAppsPage.getApplications().get(THIRD_PARTY_APP).getClientScopesGranted();
    Assert.assertEquals("Email address", displayedScopes.get(0));
    Assert.assertEquals("User profile", displayedScopes.get(1));
    // Update GUI Order --- email=3
    emailRep = emailScope.toRepresentation();
    emailRep.getAttributes().put(ClientScopeModel.GUI_ORDER, "3");
    emailScope.update(emailRep);
    // Display account mgmt --- assert profile, then email
    accountAppsPage.open();
    displayedScopes = accountAppsPage.getApplications().get(THIRD_PARTY_APP).getClientScopesGranted();
    Assert.assertEquals("User profile", displayedScopes.get(0));
    Assert.assertEquals("Email address", displayedScopes.get(1));
    // Revoke grant and display consent screen --- assert profile, then email
    accountAppsPage.revokeGrant(THIRD_PARTY_APP);
    oauth.openLoginForm();
    grantPage.assertCurrent();
    displayedScopes = grantPage.getDisplayedGrants();
    Assert.assertEquals("User profile", displayedScopes.get(0));
    Assert.assertEquals("Email address", displayedScopes.get(1));
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 5 with ClientScopeResource

use of org.keycloak.admin.client.resource.ClientScopeResource in project keycloak by keycloak.

the class AudienceTest method testAudienceProtocolMapperWithCustomAudience.

@Test
public void testAudienceProtocolMapperWithCustomAudience() throws Exception {
    // Add audience protocol mapper to the clientScope "audience-scope"
    ProtocolMapperRepresentation audienceMapper = ProtocolMapperUtil.createAudienceMapper("audience mapper 1", null, "http://host/service/ctx1", true, false);
    ClientScopeResource clientScope = ApiUtil.findClientScopeByName(testRealm(), "audience-scope");
    Response resp = clientScope.getProtocolMappers().createMapper(audienceMapper);
    String mapper1Id = ApiUtil.getCreatedId(resp);
    resp.close();
    audienceMapper = ProtocolMapperUtil.createAudienceMapper("audience mapper 2", null, "http://host/service/ctx2", true, true);
    resp = clientScope.getProtocolMappers().createMapper(audienceMapper);
    String mapper2Id = ApiUtil.getCreatedId(resp);
    resp.close();
    // Login and check audiences in the token
    oauth.scope("openid audience-scope");
    oauth.doLogin("john", "password");
    EventRepresentation loginEvent = events.expectLogin().user(userId).assertEvent();
    Tokens tokens = sendTokenRequest(loginEvent, userId, "openid profile email audience-scope", "test-app");
    assertAudiences(tokens.accessToken, "http://host/service/ctx1", "http://host/service/ctx2");
    assertAudiences(tokens.idToken, "test-app", "http://host/service/ctx2");
    // Revert
    clientScope.getProtocolMappers().delete(mapper1Id);
    clientScope.getProtocolMappers().delete(mapper2Id);
}
Also used : Response(javax.ws.rs.core.Response) ClientScopeResource(org.keycloak.admin.client.resource.ClientScopeResource) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) Test(org.junit.Test)

Aggregations

ClientScopeResource (org.keycloak.admin.client.resource.ClientScopeResource)8 Test (org.junit.Test)7 Response (javax.ws.rs.core.Response)5 ClientScopeRepresentation (org.keycloak.representations.idm.ClientScopeRepresentation)5 ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)4 RealmResource (org.keycloak.admin.client.resource.RealmResource)3 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)3 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)3 ClientResource (org.keycloak.admin.client.resource.ClientResource)2 AccessToken (org.keycloak.representations.AccessToken)2 IDToken (org.keycloak.representations.IDToken)2 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)2 OAuthClient (org.keycloak.testsuite.util.OAuthClient)2 URI (java.net.URI)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Client (javax.ws.rs.client.Client)1 WebTarget (javax.ws.rs.client.WebTarget)1