Search in sources :

Example 1 with ProtocolMapperRepresentation

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

the class SAMLLoginResponseHandlingTest method testAttributes.

@Test
public void testAttributes() throws Exception {
    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();
    Map<String, String> config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "topAttribute");
    config.put("attribute.name", "topAttribute");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "topAttribute", "saml", "saml-user-attribute-mapper", config));
    config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "level2Attribute");
    config.put("attribute.name", "level2Attribute");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "level2Attribute", "saml", "saml-user-attribute-mapper", config));
    config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("single", "true");
    config.put("attribute.name", "group");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "groups", "saml", "saml-group-membership-mapper", config));
    setRolesToCheck("manager,user");
    employee2ServletPage.navigateTo();
    assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
    testRealmSAMLPostLoginPage.form().login("level2GroupUser", "password");
    driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
    waitUntilElement(By.xpath("//body")).text().contains("topAttribute: true");
    waitUntilElement(By.xpath("//body")).text().contains("level2Attribute: true");
    waitUntilElement(By.xpath("//body")).text().contains(X500SAMLProfileConstants.EMAIL.get() + ": level2@redhat.com");
    waitUntilElement(By.xpath("//body")).text().not().contains("group: []");
    waitUntilElement(By.xpath("//body")).text().not().contains("group: null");
    waitUntilElement(By.xpath("//body")).text().not().contains("group: <br />");
    waitUntilElement(By.xpath("//body")).text().contains("group: level2");
    employee2ServletPage.logout();
    checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    setRolesToCheck("manager,employee,user");
    employee2ServletPage.navigateTo();
    assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
    testRealmSAMLPostLoginPage.form().login(bburkeUser);
    driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
    waitUntilElement(By.xpath("//body")).text().contains(X500SAMLProfileConstants.EMAIL.get() + ": bburke@redhat.com");
    waitUntilElement(By.xpath("//body")).text().contains("friendly email: bburke@redhat.com");
    waitUntilElement(By.xpath("//body")).text().contains("phone: 617");
    waitUntilElement(By.xpath("//body")).text().not().contains("friendly phone:");
    driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL());
    waitForPageToLoad();
    Assert.assertEquals("", getRawPageSource());
    employee2ServletPage.logout();
    checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    config = new LinkedHashMap<>();
    config.put("attribute.value", "hard");
    config.put("attribute.nameformat", "Basic");
    config.put("attribute.name", "hardcoded-attribute");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "hardcoded-attribute", "saml", "saml-hardcode-attribute-mapper", config));
    config = new LinkedHashMap<>();
    config.put("role", "hardcoded-role");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "hardcoded-role", "saml", "saml-hardcode-role-mapper", config));
    config = new LinkedHashMap<>();
    config.put("new.role.name", "pee-on");
    config.put("role", "http://localhost:8280/employee/.employee");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "renamed-employee-role", "saml", "saml-role-name-mapper", config));
    for (ProtocolMapperRepresentation mapper : clientResource.toRepresentation().getProtocolMappers()) {
        if (mapper.getName().equals("role-list")) {
            protocolMappersResource.delete(mapper.getId());
            Map<String, String> origConfig = new HashMap<>(mapper.getConfig());
            mapper.setId(null);
            mapper.getConfig().put(RoleListMapper.SINGLE_ROLE_ATTRIBUTE, "true");
            mapper.getConfig().put(AttributeStatementHelper.SAML_ATTRIBUTE_NAME, "memberOf");
            try (Response response = protocolMappersResource.createMapper(mapper)) {
                String createdId = getCreatedId(response);
                getCleanup().addCleanup((Runnable) () -> {
                    protocolMappersResource.delete(createdId);
                    mapper.setConfig(origConfig);
                    protocolMappersResource.createMapper(mapper).close();
                });
            }
        }
    }
    setRolesToCheck("pee-on,el-jefe,manager,hardcoded-role");
    config = new LinkedHashMap<>();
    config.put("new.role.name", "el-jefe");
    config.put("role", "user");
    getCleanup().addCleanup(createProtocolMapper(protocolMappersResource, "renamed-role", "saml", "saml-role-name-mapper", config));
    employee2ServletPage.navigateTo();
    assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
    testRealmSAMLPostLoginPage.form().login(bburkeUser);
    driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
    waitUntilElement(By.xpath("//body")).text().contains("hardcoded-attribute: hard");
    employee2ServletPage.checkRolesEndPoint(false);
    employee2ServletPage.logout();
    checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
}
Also used : Response(javax.ws.rs.core.Response) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) Matchers.containsString(org.hamcrest.Matchers.containsString) ProtocolMappersResource(org.keycloak.admin.client.resource.ProtocolMappersResource) LinkedHashMap(java.util.LinkedHashMap) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 2 with ProtocolMapperRepresentation

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

the class AbstractSAMLServletAdapterTest method createProtocolMapper.

protected AutoCloseable createProtocolMapper(ProtocolMappersResource resource, String name, String protocol, String protocolMapper, Map<String, String> config) {
    ProtocolMapperRepresentation representation = new ProtocolMapperRepresentation();
    representation.setName(name);
    representation.setProtocol(protocol);
    representation.setProtocolMapper(protocolMapper);
    representation.setConfig(config);
    try (Response response = resource.createMapper(representation)) {
        String createdId = getCreatedId(response);
        return () -> resource.delete(createdId);
    }
}
Also used : CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Response(javax.ws.rs.core.Response) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation)

Example 3 with ProtocolMapperRepresentation

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

the class ClientRegistrationPoliciesTest method testProtocolMappersUpdate.

@Test
// We would need to do domain name -> ip address to set trusted host
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testProtocolMappersUpdate() throws Exception {
    setTrustedHost("localhost");
    // Check I can add client with allowed protocolMappers
    ProtocolMapperRepresentation protocolMapper = new ProtocolMapperRepresentation();
    protocolMapper.setName("Full name");
    protocolMapper.setProtocolMapper(FullNameMapper.PROVIDER_ID);
    protocolMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    ClientRepresentation clientRep = createRep("test-app");
    clientRep.setProtocolMappers(Collections.singletonList(protocolMapper));
    ClientRepresentation registeredClient = reg.create(clientRep);
    reg.auth(Auth.token(registeredClient));
    // Add some disallowed protocolMapper
    registeredClient.getProtocolMappers().add(createHardcodedMapperRep());
    // Check I can't update client because of protocolMapper
    assertFail(ClientRegOp.UPDATE, registeredClient, 403, "ProtocolMapper type not allowed");
    // Remove "bad" protocolMapper
    registeredClient.getProtocolMappers().removeIf((ProtocolMapperRepresentation mapper) -> {
        return mapper.getProtocolMapper().equals(HardcodedRole.PROVIDER_ID);
    });
    // Check I can update client now
    reg.update(registeredClient);
    // Revert client
    ApiUtil.findClientResourceByClientId(realmResource(), "test-app").remove();
}
Also used : ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 4 with ProtocolMapperRepresentation

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

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

the class OIDCProtocolMappersTest method makeMapper.

private ProtocolMapperRepresentation makeMapper(String name, String mapperType, Map<String, String> config) {
    ProtocolMapperRepresentation rep = new ProtocolMapperRepresentation();
    rep.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    rep.setName(name);
    rep.setProtocolMapper(mapperType);
    rep.setConfig(config);
    return rep;
}
Also used : ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation)

Aggregations

ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)107 Test (org.junit.Test)68 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)30 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)27 Map (java.util.Map)23 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)20 ClientResource (org.keycloak.admin.client.resource.ClientResource)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)17 RealmResource (org.keycloak.admin.client.resource.RealmResource)14 List (java.util.List)13 ProtocolMappersResource (org.keycloak.admin.client.resource.ProtocolMappersResource)12 IDToken (org.keycloak.representations.IDToken)12 Matchers.isEmptyOrNullString (org.hamcrest.Matchers.isEmptyOrNullString)11 ClientScopeRepresentation (org.keycloak.representations.idm.ClientScopeRepresentation)11 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)10 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)8 ArrayList (java.util.ArrayList)7 LinkedList (java.util.LinkedList)7 AccessToken (org.keycloak.representations.AccessToken)7