org.keycloak.representations.idm.ProtocolMapperRepresentation Java Examples

The following examples show how to use org.keycloak.representations.idm.ProtocolMapperRepresentation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientMappersOIDCTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserSessionNote() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("user session note");
    createClientMappersPage.form().setMapperType(USER_SESSION_NOTE);
    createClientMappersPage.form().setUserSessionNote("session note");
    createClientMappersPage.form().setTokenClaimName("claim name");
    createClientMappersPage.form().setClaimJSONType("int");
    createClientMappersPage.form().setAddToIDToken(false);
    createClientMappersPage.form().setAddToAccessToken(false);
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "user session note");
    assertNotNull(found);

    assertEquals("oidc-usersessionmodel-note-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("claim name", config.get("claim.name"));
    assertEquals("session note", config.get("user.session.note"));
    assertEquals("int", config.get("jsonType.label"));
}
 
Example #2
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidAudience() {
    loginUser();
    logoutFromRealm(getProviderRoot(), bc.providerRealmName());
    logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

    log.debug("Clicking social " + bc.getIDPAlias());
    loginPage.clickSocial(bc.getIDPAlias());
    waitForPage(driver, "log in to", true);

    RealmResource realm = adminClient.realm(bc.providerRealmName());
    ClientRepresentation rep = realm.clients().findByClientId(BrokerTestConstants.CLIENT_ID).get(0);
    ClientResource clientResource = realm.clients().get(rep.getId());
    ProtocolMapperRepresentation hardCodedAzp = createHardcodedClaim("hard", "aud", "invalid-aud", ProviderConfigProperty.LIST_TYPE, true, true);
    clientResource.getProtocolMappers().createMapper(hardCodedAzp);

    log.debug("Logging in");
    loginPage.login(bc.getUserLogin(), bc.getUserPassword());
    errorPage.assertCurrent();
}
 
Example #3
Source File: ClientMappersSAMLTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testHardcodedAttribute() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("hardcoded attribute");
    createClientMappersPage.form().setMapperType(HARDCODED_ATTRIBUTE);
    createClientMappersPage.form().setAttributeValue("attribute value");
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "hardcoded attribute");
    assertNotNull(found);

    assertEquals("saml-hardcode-attribute-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("attribute value", config.get("attribute.value"));
}
 
Example #4
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper3");

    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    samlMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), ResourceType.PROTOCOL_MAPPER);

    try {
        samlMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
        // Expected
    }
}
 
Example #5
Source File: ClientMappersSAMLTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoleList() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("new role list");
    createClientMappersPage.form().setMapperType(ROLE_LIST);
    createClientMappersPage.form().setRoleAttributeName("role attribute name");
    createClientMappersPage.form().setFriendlyName("friendly name");
    createClientMappersPage.form().setSamlAttributeNameFormat("URI Reference");
    createClientMappersPage.form().setSingleRoleAttribute(true);
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "new role list");
    assertNotNull(found);

    assertEquals("saml-role-list-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("role attribute name", config.get("attribute.name"));
    assertEquals("URI Reference", config.get("attribute.nameformat"));
    assertEquals("friendly name", config.get("friendly.name"));
    assertEquals("true", config.get("single"));
}
 
Example #6
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test07UpdateOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper2");

    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(oidcClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    rep.getConfig().put("role", "myotherrole");
    rep.setId(createdId);
    oidcMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientScopeProtocolMapperPath(oidcClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    ProtocolMapperRepresentation updated = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}
 
Example #7
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test06UpdateSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper2");

    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    rep.getConfig().put("role", "account.manage-account");
    rep.setId(createdId);
    samlMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    ProtocolMapperRepresentation updated = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}
 
Example #8
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test04CreateSamlProtocolMapper() {

    //{"protocol":"saml",
    // "config":{"role":"account.view-profile","new.role.name":"new-role-name"},
    // "consentRequired":true,
    // "consentText":"My consent text",
    // "name":"saml-role-name-maper",
    // "protocolMapper":"saml-role-name-mapper"}
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper");

    int totalMappers = samlMappersRsc.getMappers().size();
    int totalSamlMappers = samlMappersRsc.getMappersPerProtocol("saml").size();
    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);

    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    assertEquals(totalMappers + 1, samlMappersRsc.getMappers().size());
    assertEquals(totalSamlMappers + 1, samlMappersRsc.getMappersPerProtocol("saml").size());

    ProtocolMapperRepresentation created = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, created);
}
 
Example #9
Source File: ProtocolMappersResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Create multiple mappers
 *
 */
@Path("add-models")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public void createMapper(List<ProtocolMapperRepresentation> reps) {
    managePermission.require();

    ProtocolMapperModel model = null;
    for (ProtocolMapperRepresentation rep : reps) {
        model = RepresentationToModel.toModel(rep);
        validateModel(model);
        model = client.addProtocolMapper(model);
    }
    adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri()).representation(reps).success();
}
 
Example #10
Source File: ClientProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test06UpdateSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper2");

    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    rep.getConfig().put("role", "account.manage-account");
    rep.setId(createdId);
    samlMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    ProtocolMapperRepresentation updated = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}
 
Example #11
Source File: ClientMappersOIDCTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserAttribute() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("user attribute");
    createClientMappersPage.form().setMapperType(USER_ATTRIBUTE);
    createClientMappersPage.form().setUserAttribute("user attribute");
    createClientMappersPage.form().setMultivalued(true);
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "user attribute");
    assertEquals("oidc-usermodel-attribute-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("true", config.get("multivalued"));
    assertEquals("user attribute", config.get("user.attribute"));
}
 
Example #12
Source File: ClientProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test08DeleteSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper3");

    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    samlMappersRsc.delete(createdId);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(samlClientId, createdId), ResourceType.PROTOCOL_MAPPER);

    try {
        samlMappersRsc.getMapperById(createdId);
        Assert.fail("Not expected to find mapper");
    } catch (NotFoundException nfe) {
        // Expected
    }
}
 
Example #13
Source File: ClientMappersOIDCTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserProperty() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("user property");
    createClientMappersPage.form().setMapperType(USER_PROPERTY);
    createClientMappersPage.form().setProperty("property");
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "user property");
    assertEquals("oidc-usermodel-property-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("property", config.get("user.attribute"));
}
 
Example #14
Source File: OpenShiftTokenReviewEndpointTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    ClientRepresentation client = testRealm.getClients().stream().filter(r -> r.getClientId().equals("test-app")).findFirst().get();

    List<ProtocolMapperRepresentation> mappers = new LinkedList<>();
    ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation();
    mapper.setName("groups");
    mapper.setProtocolMapper(GroupMembershipMapper.PROVIDER_ID);
    mapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    Map<String, String> config = new HashMap<>();
    config.put("full.path", "false");
    config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "groups");
    config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    mapper.setConfig(config);
    mappers.add(mapper);

    client.setProtocolMappers(mappers);
    client.setPublicClient(false);
    client.setClientAuthenticatorType("testsuite-client-dummy");

    testRealm.getUsers().add(UserBuilder.create().username("groups-user").password("password").addGroups("/topGroup", "/topGroup/level2group").build());
}
 
Example #15
Source File: DefaultMigrationProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public List<ProtocolMapperRepresentation> getMappersForClaimMask(Long claimMask) {
    Map<String, ProtocolMapperRepresentation> allMappers = getAllDefaultMappers(session);

    if (claimMask == null) {
        return new ArrayList<ProtocolMapperRepresentation>(allMappers.values());
    }

    if (!ClaimMask.hasUsername(claimMask)) {
        allMappers.remove(OIDCLoginProtocolFactory.USERNAME);
    }
    if (!ClaimMask.hasEmail(claimMask)) {
        allMappers.remove(OIDCLoginProtocolFactory.EMAIL);
    }
    if (!ClaimMask.hasName(claimMask)) {
        allMappers.remove(OIDCLoginProtocolFactory.FAMILY_NAME);
        allMappers.remove(OIDCLoginProtocolFactory.FULL_NAME);
        allMappers.remove(OIDCLoginProtocolFactory.GIVEN_NAME);
    }

    return new ArrayList<ProtocolMapperRepresentation>(allMappers.values());
}
 
Example #16
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidIssuedFor() {
    loginUser();
    logoutFromRealm(getProviderRoot(), bc.providerRealmName());
    logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

    log.debug("Clicking social " + bc.getIDPAlias());
    loginPage.clickSocial(bc.getIDPAlias());
    waitForPage(driver, "log in to", true);

    RealmResource realm = adminClient.realm(bc.providerRealmName());
    ClientRepresentation rep = realm.clients().findByClientId(BrokerTestConstants.CLIENT_ID).get(0);
    ClientResource clientResource = realm.clients().get(rep.getId());
    ProtocolMapperRepresentation hardCodedAzp = createHardcodedClaim("hard", "azp", "invalid-azp", ProviderConfigProperty.STRING_TYPE, true, true);
    clientResource.getProtocolMappers().createMapper(hardCodedAzp);

    log.debug("Logging in");
    loginPage.login(bc.getUserLogin(), bc.getUserPassword());
    errorPage.assertCurrent();
}
 
Example #17
Source File: ClientMappersSAMLTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupList() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("group list");
    createClientMappersPage.form().setMapperType(GROUP_LIST);
    createClientMappersPage.form().setGroupAttributeName("group attribute name");
    createClientMappersPage.form().setSingleGroupAttribute(true);
    createClientMappersPage.form().setFullGroupPath(true);
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "group list");
    assertEquals("saml-group-membership-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("true", config.get("full.path"));
    assertEquals("true", config.get("single"));
    assertEquals("group attribute name", config.get("attribute.name"));
}
 
Example #18
Source File: ClientMappersOIDCTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupMembership() {
    //create
    clientMappersPage.mapperTable().createMapper();
    setInitialValues("group membership");
    createClientMappersPage.form().setMapperType(GROUP_MEMBERSHIP);
    createClientMappersPage.form().setFullGroupPath(true);
    createClientMappersPage.form().save();
    assertAlertSuccess();
    
    //check
    ProtocolMapperRepresentation found = findClientMapperByName(id, "group membership");
    assertEquals("oidc-group-membership-mapper", found.getProtocolMapper());
    
    Map<String, String> config = found.getConfig();
    assertEquals("true", config.get("full.path"));
}
 
Example #19
Source File: ClientRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
public void updateProtocolMappers(String realm, String clientId, List<ProtocolMapperRepresentation> protocolMappers) {
    ClientResource clientResource = loadClientById(realm, clientId);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    for (ProtocolMapperRepresentation protocolMapper : protocolMappers) {
        try {
            protocolMappersResource.update(protocolMapper.getId(), protocolMapper);
        } catch (WebApplicationException error) {
            String errorMessage = ResponseUtil.getErrorMessage(error);
            throw new ImportProcessingException(
                    "Cannot update protocolMapper '" + protocolMapper.getName()
                            + "' for client '" + clientResource.toRepresentation().getClientId()
                            + "' for realm '" + realm + "'"
                            + ": " + errorMessage,
                    error
            );
        }
    }
}
 
Example #20
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void testAccountConsoleClient(RealmResource realm) {
    ClientRepresentation accountConsoleClient = realm.clients().findByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID).get(0);

    assertEquals(Constants.AUTH_BASE_URL_PROP, accountConsoleClient.getRootUrl());
    assertEquals("/realms/" + realm.toRepresentation().getRealm() + "/account/", accountConsoleClient.getBaseUrl());
    assertTrue(accountConsoleClient.isPublicClient());
    assertFalse(accountConsoleClient.isFullScopeAllowed());
    assertTrue(accountConsoleClient.isStandardFlowEnabled());
    assertFalse(accountConsoleClient.isDirectAccessGrantsEnabled());
    assertEquals("S256", accountConsoleClient.getAttributes().get(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD));

    ClientResource clientResource = realm.clients().get(accountConsoleClient.getId());

    MappingsRepresentation scopes = clientResource.getScopeMappings().getAll();
    assertNull(scopes.getRealmMappings());
    assertEquals(1, scopes.getClientMappings().size());
    assertEquals(1, scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings().size());
    assertEquals(MANAGE_ACCOUNT, scopes.getClientMappings().get(ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings().get(0).getName());

    List<ProtocolMapperRepresentation> mappers = clientResource.getProtocolMappers().getMappers();
    assertEquals(1, mappers.size());
    assertEquals("oidc-audience-resolve-mapper", mappers.get(0).getProtocolMapper());
}
 
Example #21
Source File: OIDCPairwiseClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateToPairwiseThroughAdminRESTFailure() throws Exception {
    OIDCClientRepresentation response = create();
    Assert.assertEquals("public", response.getSubjectType());
    Assert.assertNull(response.getSectorIdentifierUri());

    // Push empty list to the sector identifier URI
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setSectorIdentifierRedirectUris(new ArrayList<>());

    String sectorIdentifierUri = TestApplicationResourceUrls.pairwiseSectorIdentifierUri();

    // Add protocolMapper through admin REST endpoint
    String clientId = response.getClientId();
    ProtocolMapperRepresentation pairwiseProtMapper = SHA256PairwiseSubMapper.createPairwiseMapper(sectorIdentifierUri, null);
    RealmResource realmResource = realmsResouce().realm("test");
    ClientResource clientResource = ApiUtil.findClientByClientId(realmsResouce().realm("test"), clientId);
    Response resp = clientResource.getProtocolMappers().createMapper(pairwiseProtMapper);
    Assert.assertEquals(400, resp.getStatus());

    // Assert still public
    reg.auth(Auth.token(response));
    OIDCClientRepresentation rep = reg.oidc().get(response.getClientId());
    Assert.assertEquals("public", rep.getSubjectType());
    Assert.assertNull(rep.getSectorIdentifierUri());
}
 
Example #22
Source File: ClientScopeRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
public void updateProtocolMappers(String realm, String clientScopeId, List<ProtocolMapperRepresentation> protocolMappers) {
    ClientScopeResource clientScopeResource = loadClientScopeById(realm, clientScopeId);
    ProtocolMappersResource protocolMappersResource = clientScopeResource.getProtocolMappers();

    for (ProtocolMapperRepresentation protocolMapper : protocolMappers) {
        try {
            protocolMappersResource.update(protocolMapper.getId(), protocolMapper);
        } catch (WebApplicationException error) {
            String errorMessage = ResponseUtil.getErrorMessage(error);
            throw new ImportProcessingException(
                    "Cannot update protocolMapper '" + protocolMapper.getName()
                            + "' for clientScope '" + clientScopeResource.toRepresentation().getName()
                            + "' for realm '" + realm + "'"
                            + ": " + errorMessage,
                    error
            );
        }
    }
}
 
Example #23
Source File: AudienceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testAudienceProtocolMapperWithClientAudience() throws Exception {
    // Add audience protocol mapper to the clientScope "audience-scope"
    ProtocolMapperRepresentation audienceMapper = ProtocolMapperUtil.createAudienceMapper("audience mapper", "service-client",
            null, true, false);
    ClientScopeResource clientScope = ApiUtil.findClientScopeByName(testRealm(), "audience-scope");
    Response resp = clientScope.getProtocolMappers().createMapper(audienceMapper);
    String mapperId = ApiUtil.getCreatedId(resp);
    resp.close();

    // Login and check audiences in the token (just accessToken contains it)
    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, "service-client");
    assertAudiences(tokens.idToken, "test-app");

    // Revert
    clientScope.getProtocolMappers().delete(mapperId);
}
 
Example #24
Source File: ClientRegistrationPoliciesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ProtocolMapperRepresentation createHardcodedMapperRep() {
    ProtocolMapperRepresentation protocolMapper = new ProtocolMapperRepresentation();
    protocolMapper.setName("Hardcoded foo role");
    protocolMapper.setProtocolMapper(HardcodedRole.PROVIDER_ID);
    protocolMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    protocolMapper.getConfig().put(HardcodedRole.ROLE_CONFIG, "foo-role");
    return protocolMapper;
}
 
Example #25
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testUserGroupRoleToAttributeMappers() throws Exception {
    // Add mapper for realm roles
    String clientId = "test-app";
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, "ta.", "Client roles mapper", "roles-custom.test-app", true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));

    // Login user
    OAuthClient.AccessTokenResponse response = browserLogin("password", "[email protected]", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId));
    String realmRoleMappings = (String) roleMappings.get("realm");
    String testAppMappings = (String) roleMappings.get(clientId);
    assertRolesString(realmRoleMappings,
      "pref.admin",                     // from direct assignment to /roleRichGroup/level2group
      "pref.user",                      // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
      "pref.customer-user-premium",     // from client role customer-admin-composite-role - realm role for test-app
      "pref.realm-composite-role",      // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
      "pref.sample-realm-role"          // from realm role realm-composite-role
    );
    assertRolesString(testAppMappings,
      "ta.customer-user",                  // from direct assignment to /roleRichGroup/level2group
      "ta.customer-admin-composite-role",  // from direct assignment to /roleRichGroup/level2group
      "ta.customer-admin",                 // from client role customer-admin-composite-role - client role for test-app
      "ta.sample-client-role"              // from realm role realm-composite-role - client role for test-app
    );

    // Revert
    deleteMappers(protocolMappers);
}
 
Example #26
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-4205
 * @throws Exception
 */
@Test
public void testUserRoleToAttributeMappersWithMultiValuedRoles() throws Exception {
    // Add mapper for realm roles
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper("test-app", null, "Client roles mapper", "roles-custom.test-app", true, true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));

    // Login user
    OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", "test-app"));
    Assert.assertThat(roleMappings.get("realm"), CoreMatchers.instanceOf(List.class));
    Assert.assertThat(roleMappings.get("test-app"), CoreMatchers.instanceOf(List.class));

    List<String> realmRoleMappings = (List<String>) roleMappings.get("realm");
    List<String> testAppMappings = (List<String>) roleMappings.get("test-app");
    assertRoles(realmRoleMappings,
            "pref.user",                      // from direct assignment in user definition
            "pref.offline_access"             // from direct assignment in user definition
    );
    assertRoles(testAppMappings,
            "customer-user"                   // from direct assignment in user definition
    );

    // Revert
    deleteMappers(protocolMappers);
}
 
Example #27
Source File: ServerInfoAdminResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setBuiltinProtocolMappers(ServerInfoRepresentation info) {
    info.setBuiltinProtocolMappers(new HashMap<String, List<ProtocolMapperRepresentation>>());
    for (ProviderFactory p : session.getKeycloakSessionFactory().getProviderFactories(LoginProtocol.class)) {
        LoginProtocolFactory factory = (LoginProtocolFactory)p;
        List<ProtocolMapperRepresentation> mappers = new LinkedList<>();
        for (ProtocolMapperModel mapper : factory.getBuiltinMappers().values()) {
            mappers.add(ModelToRepresentation.toRepresentation(mapper));
        }
        info.getBuiltinProtocolMappers().put(p.getId(), mappers);
    }
}
 
Example #28
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserGroupRoleToAttributeMappersScopedClientNotSet() throws Exception {
    String clientId = "test-app-scope";
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(null, null, "Client roles mapper", "roles-custom.test-app-scope", true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));

    // Login user
    ClientManager.realm(adminClient.realm("test")).clientId(clientId).directAccessGrant(true);
    oauth.clientId(clientId);
    OAuthClient.AccessTokenResponse response = browserLogin("password", "[email protected]", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId));
    String realmRoleMappings = (String) roleMappings.get("realm");
    String testAppScopeMappings = (String) roleMappings.get(clientId);
    assertRolesString(realmRoleMappings,
      "pref.admin",                     // from direct assignment to /roleRichGroup/level2group
      "pref.user",  // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
      "pref.customer-user-premium"
    );
    assertRolesString(testAppScopeMappings,
      "test-app-allowed-by-scope",      // from direct assignment to roleRichUser, present as scope allows it
      "test-app-disallowed-by-scope"   // from direct assignment to /roleRichGroup/level2group, present as scope allows it
    );

    // Revert
    deleteMappers(protocolMappers);
}
 
Example #29
Source File: ClientMapperSetup.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
private ProtocolMapperRepresentation createGroupMapper() {
    ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation();
    protocolMapperRepresentation.setProtocolMapper(GroupMembershipMapper.PROVIDER_ID);
    protocolMapperRepresentation.setProtocol(PROTOCOL);
    protocolMapperRepresentation.setName("Group mapper");
    Map<String, String> config = new HashMap<>();
    putAccessTokenClaim(config);
    // the name of the property we got from the class GroupMembershipMapper
    config.put("full.path", "true");
    config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "groups");
    protocolMapperRepresentation.setConfig(config);
    return protocolMapperRepresentation;
}
 
Example #30
Source File: ProtocolMapperUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ProtocolMapperRepresentation createClaimMapper(String name,
                                                             String userSessionNote,
                                                             String tokenClaimName, String jsonType,
                                                             boolean accessToken, boolean idToken) {

    return ModelToRepresentation.toRepresentation(UserSessionNoteMapper.createClaimMapper(name,
            userSessionNote,
            tokenClaimName, jsonType,
            accessToken, idToken));
}