org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper Java Examples

The following examples show how to use org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper. 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: AbstractClaimMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static Object getClaimValue(JsonWebToken token, String claim) {

        switch (claim) {
            case "sub":
                return token.getSubject();
            default:
                // found no match, try other claims
        }

        List<String> split = OIDCAttributeMapperHelper.splitClaimPath(claim);
        Map<String, Object> jsonObject = token.getOtherClaims();
        final int length = split.size();
        int i = 0;
        for (String component : split) {
            i++;
            if (i == length) {
                return jsonObject.get(component);
            } else {
                Object val = jsonObject.get(component);
                if (!(val instanceof Map)) return null;
                jsonObject = (Map<String, Object>)val;
            }
        }
        return null;
    }
 
Example #2
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 #3
Source File: OriginalSubClaimMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCtx) {

    RealmModel realm = userSession.getRealm();
    UserModel user = userSession.getUser();

    List<IdentityProviderModel> identityProviders = realm.getIdentityProviders();
    Set<FederatedIdentityModel> identities = session.users().getFederatedIdentities(user, realm);

    if (identityProviders == null || identityProviders.isEmpty()) {
        return;
    }

    for (IdentityProviderModel provider : identityProviders) {
        if (!provider.isEnabled()) {
            continue;
        }

        String providerId = provider.getAlias();
        FederatedIdentityModel identity = getIdentity(identities, providerId);

        if (identity != null) {
            String userId = identity.getUserId();
            OIDCAttributeMapperHelper.mapClaim(token, mappingModel, userId);
        }
    }
}
 
Example #4
Source File: VirtualClientModelGenerator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private static Set<ProtocolMapperModel> createDefaultProtocolMappers() {

        Set<ProtocolMapperModel> mappers = new LinkedHashSet<>();

        ProtocolMapperModel clientIdMapper = UserSessionNoteMapper.createClaimMapper(
                ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER,
                ServiceAccountConstants.CLIENT_ID,
                ServiceAccountConstants.CLIENT_ID,
                "String",
                true,
                true);
        clientIdMapper.setId(KeycloakModelUtils.generateId());
        mappers.add(clientIdMapper);

        ProtocolMapperModel dynamicMapperModel = new ProtocolMapperModel();
        dynamicMapperModel.setName(DynamicClaimMapper.PROVIDER_ID);
        dynamicMapperModel.setId(KeycloakModelUtils.generateId());
        dynamicMapperModel.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        dynamicMapperModel.setProtocolMapper(DynamicClaimMapper.PROVIDER_ID);
        Map<String, String> config = new HashMap<>();
        config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
        config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "false");
        dynamicMapperModel.setConfig(config);
        mappers.add(dynamicMapperModel);

        return mappers;
    }
 
Example #5
Source File: SimpleOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

    Object claimValue = mappingModel.getConfig().getOrDefault(CONFIG_PROPERTY, "defaultProperty");
    LOGGER.infof("setClaim %s=%s", mappingModel.getName(), claimValue);

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #6
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 #7
Source File: ClientMapperSetup.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
private ProtocolMapperRepresentation createHelloWordMapper() {
    ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation();
    protocolMapperRepresentation.setProtocolMapper(HelloWorldMapper.PROVIDER_ID);
    protocolMapperRepresentation.setProtocol(PROTOCOL);
    protocolMapperRepresentation.setName("Hello world mapper");
    Map<String, String> config = new HashMap<>();
    putAccessTokenClaim(config);
    config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "example.message");
    protocolMapperRepresentation.setConfig(config);
    return protocolMapperRepresentation;
}
 
Example #8
Source File: HelloWorldMapper.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(final IDToken token, final ProtocolMapperModel mappingModel, final UserSessionModel userSession, final KeycloakSession keycloakSession) {
    // adds our data to the token. Uses the parameters like the claim name which were set by the user
    // when this protocol mapper was configured in keycloak. Note that the parameters which can
    // be configured in keycloak for this protocol mapper were set in the static intializer of this class.
    //
    // Sets a static "Hello world" string, but we could write a dynamic value like a group attribute here too.
    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, "hello world");
}
 
Example #9
Source File: HelloWorldMapperTest.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHaveProperties() {
    final List<String> configPropertyNames = new HelloWorldMapper().getConfigProperties().stream()
            .map(ProviderConfigProperty::getName)
            .collect(Collectors.toList());
    assertThat(configPropertyNames).containsExactly(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO);
}
 
Example #10
Source File: AbstractCASProtocolMapper.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
protected void setPlainAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, Object attributeValue) {
    String protocolClaim = mappingModel.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME);
    if (protocolClaim == null || attributeValue == null) {
        return;
    }
    attributes.put(protocolClaim, attributeValue);
}
 
Example #11
Source File: CASAttributeMapperHelper.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
public static ProtocolMapperModel createClaimMapper(String name,
                                                    String tokenClaimName, String claimType,
                                                    String mapperId) {
    ProtocolMapperModel mapper = new ProtocolMapperModel();
    mapper.setName(name);
    mapper.setProtocolMapper(mapperId);
    mapper.setProtocol(CASLoginProtocol.LOGIN_PROTOCOL);
    Map<String, String> config = new HashMap<String, String>();
    config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, tokenClaimName);
    config.put(OIDCAttributeMapperHelper.JSON_TYPE, claimType);
    mapper.setConfig(config);
    return mapper;
}
 
Example #12
Source File: ExportImportUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void assertGssProtocolMapper(ProtocolMapperRepresentation gssCredentialMapper) {
    Assert.assertEquals(KerberosConstants.GSS_DELEGATION_CREDENTIAL_DISPLAY_NAME, gssCredentialMapper.getName());
    Assert.assertEquals( OIDCLoginProtocol.LOGIN_PROTOCOL, gssCredentialMapper.getProtocol());
    Assert.assertEquals(UserSessionNoteMapper.PROVIDER_ID, gssCredentialMapper.getProtocolMapper());
    String includeInAccessToken = gssCredentialMapper.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN);
    String includeInIdToken = gssCredentialMapper.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN);
    Assert.assertTrue(includeInAccessToken.equalsIgnoreCase("true"));
    Assert.assertTrue(includeInIdToken == null || Boolean.parseBoolean(includeInIdToken) == false);
}
 
Example #13
Source File: AbstractCASProtocolMapper.java    From keycloak-protocol-cas with Apache License 2.0 4 votes vote down vote up
protected void setMappedAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, Object attributeValue) {
    setPlainAttribute(attributes, mappingModel, OIDCAttributeMapperHelper.mapAttributeValue(mappingModel, attributeValue));
}
 
Example #14
Source File: AbstractJsonUserAttributeMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static Object getJsonValue(JsonNode baseNode, String fieldPath) {
	logger.debug("Going to process JsonNode path " + fieldPath + " on data " + baseNode);
	if (baseNode != null) {

		List<String> fields = OIDCAttributeMapperHelper.splitClaimPath(fieldPath);
		if (fields.isEmpty() || fieldPath.endsWith(".")) {
			logger.debug("JSON path is invalid " + fieldPath);
			return null;
		}

		JsonNode currentNode = baseNode;
		for (String currentFieldName : fields) {

			// if array path, retrieve field name and index
			String currentNodeName = currentFieldName;
			int arrayIndex = -1;
			if (currentFieldName.endsWith("]")) {
				int bi = currentFieldName.indexOf("[");
				if (bi == -1) {
					logger.debug("Invalid array index construct in " + currentFieldName);
					return null;
				}
				try {
					String is = currentFieldName.substring(bi + 1, currentFieldName.length() - 1).trim();
					arrayIndex = Integer.parseInt(is);
					if( arrayIndex < 0) throw new ArrayIndexOutOfBoundsException();
				} catch (Exception e) {
					logger.debug("Invalid array index construct in " + currentFieldName);
					return null;
				}
				currentNodeName = currentFieldName.substring(0, bi).trim();
			}

			currentNode = currentNode.get(currentNodeName);
			if (arrayIndex > -1 && currentNode.isArray()) {
				logger.debug("Going to take array node at index " + arrayIndex);
				currentNode = currentNode.get(arrayIndex);
			}

			if (currentNode == null) {
				logger.debug("JsonNode not found for name " + currentFieldName);
				return null;
			}

			if (currentNode.isArray()) {
				List<String> values = new ArrayList<>();
				for (JsonNode childNode : currentNode) {
					if (childNode.isTextual()) {
						values.add(childNode.textValue());
					} else {
						logger.warn("JsonNode in array is not text value " + childNode);
					}
				}
				if (values.isEmpty()) {
					return null;
				}
				return values ;
			} else if (currentNode.isNull()) {

				logger.debug("JsonNode is null node for name " + currentFieldName);
				return null;
			} else if (currentNode.isValueNode()) {
				String ret = currentNode.asText();
				if (ret != null && !ret.trim().isEmpty())
					return ret.trim();
				else
					return null;

			}

		}
		return currentNode;
	}
	return null;
}
 
Example #15
Source File: ClientMappersOIDCTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testEditMapper() {
    //prepare data
    ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation();
    mapper.setName("mapper name");
    //mapper.setConsentRequired(true);
    //mapper.setConsentText("consent text");
    mapper.setProtocol("openid-connect");
    mapper.setProtocolMapper("oidc-usersessionmodel-note-mapper");
    
    Map<String, String> config = new HashMap<>();
    config.put("access.token.claim", "true");
    config.put("id.token.claim", "true");
    config.put("claim.name", "claim name");
    config.put("jsonType.label", "String");
    config.put("user.session.note", "session note");
    
    mapper.setConfig(config);
    
    //insert data
    testRealmResource().clients().get(id).getProtocolMappers().createMapper(mapper).close();
    
    //check form
    clientMapperPage.setId(id);
    String mapperId = findClientMapperByName(id, "mapper name").getId();
    clientMapperPage.setMapperId(mapperId);
    clientMapperPage.navigateTo();
    
    assertEquals("openid-connect", clientMapperPage.form().getProtocol());
    assertEquals(mapperId, clientMapperPage.form().getMapperId());
    assertEquals("mapper name", clientMapperPage.form().getName());
    assertEquals("User Session Note", clientMapperPage.form().getMapperType());
    assertEquals("session note", clientMapperPage.form().getUserSessionNote());
    assertEquals("claim name", clientMapperPage.form().getTokenClaimName());
    assertEquals("String", clientMapperPage.form().getClaimJSONType());
    assertTrue(clientMapperPage.form().isAddToIDToken());
    assertTrue(clientMapperPage.form().isAddToAccessToken());
    
    //edit
    clientMapperPage.form().setAddToAccessToken(false);
    clientMapperPage.form().save();
    assertAlertSuccess();
    
    //check
    assertTrue(clientMapperPage.form().isAddToIDToken());
    assertFalse(clientMapperPage.form().isAddToAccessToken());

    ProtocolMapperRepresentation rep = findClientMapperByName(id, "mapper name");
    assertEquals("false", rep.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN));
    assertEquals("true", rep.getConfig().get(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN));

}
 
Example #16
Source File: KcOidcBrokerConfiguration.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public List<ClientRepresentation> createProviderClients() {
    ClientRepresentation client = new ClientRepresentation();
    client.setId(CLIENT_ID);
    client.setClientId(getIDPClientIdInProviderRealm());
    client.setName(CLIENT_ID);
    client.setSecret(CLIENT_SECRET);
    client.setEnabled(true);

    client.setRedirectUris(Collections.singletonList(getConsumerRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint/*"));

    client.setAdminUrl(getConsumerRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint");

    ProtocolMapperRepresentation emailMapper = new ProtocolMapperRepresentation();
    emailMapper.setName("email");
    emailMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    emailMapper.setProtocolMapper(UserPropertyMapper.PROVIDER_ID);

    Map<String, String> emailMapperConfig = emailMapper.getConfig();
    emailMapperConfig.put(ProtocolMapperUtils.USER_ATTRIBUTE, "email");
    emailMapperConfig.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "email");
    emailMapperConfig.put(OIDCAttributeMapperHelper.JSON_TYPE, ProviderConfigProperty.STRING_TYPE);
    emailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    emailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    emailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO, "true");

    ProtocolMapperRepresentation nestedAttrMapper = new ProtocolMapperRepresentation();
    nestedAttrMapper.setName("attribute - nested claim");
    nestedAttrMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    nestedAttrMapper.setProtocolMapper(UserAttributeMapper.PROVIDER_ID);

    Map<String, String> nestedEmailMapperConfig = nestedAttrMapper.getConfig();
    nestedEmailMapperConfig.put(ProtocolMapperUtils.USER_ATTRIBUTE, "nested.email");
    nestedEmailMapperConfig.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "nested.email");
    nestedEmailMapperConfig.put(OIDCAttributeMapperHelper.JSON_TYPE, ProviderConfigProperty.STRING_TYPE);
    nestedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    nestedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    nestedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO, "true");

    ProtocolMapperRepresentation dottedAttrMapper = new ProtocolMapperRepresentation();
    dottedAttrMapper.setName("attribute - claim with dot in name");
    dottedAttrMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    dottedAttrMapper.setProtocolMapper(UserAttributeMapper.PROVIDER_ID);

    Map<String, String> dottedEmailMapperConfig = dottedAttrMapper.getConfig();
    dottedEmailMapperConfig.put(ProtocolMapperUtils.USER_ATTRIBUTE, "dotted.email");
    dottedEmailMapperConfig.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "dotted\\.email");
    dottedEmailMapperConfig.put(OIDCAttributeMapperHelper.JSON_TYPE, ProviderConfigProperty.STRING_TYPE);
    dottedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    dottedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    dottedEmailMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO, "true");

    ProtocolMapperRepresentation userAttrMapper = new ProtocolMapperRepresentation();
    userAttrMapper.setName("attribute - name");
    userAttrMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    userAttrMapper.setProtocolMapper(UserAttributeMapper.PROVIDER_ID);

    Map<String, String> userAttrMapperConfig = userAttrMapper.getConfig();
    userAttrMapperConfig.put(ProtocolMapperUtils.USER_ATTRIBUTE, ATTRIBUTE_TO_MAP_NAME);
    userAttrMapperConfig.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, ATTRIBUTE_TO_MAP_NAME);
    userAttrMapperConfig.put(OIDCAttributeMapperHelper.JSON_TYPE, ProviderConfigProperty.STRING_TYPE);
    userAttrMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    userAttrMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    userAttrMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO, "true");
    userAttrMapperConfig.put(ProtocolMapperUtils.MULTIVALUED, "true");

    ProtocolMapperRepresentation userAttrMapper2 = new ProtocolMapperRepresentation();
    userAttrMapper2.setName("attribute - name - 2");
    userAttrMapper2.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    userAttrMapper2.setProtocolMapper(UserAttributeMapper.PROVIDER_ID);

    Map<String, String> userAttrMapperConfig2 = userAttrMapper2.getConfig();
    userAttrMapperConfig2.put(ProtocolMapperUtils.USER_ATTRIBUTE, ATTRIBUTE_TO_MAP_NAME_2);
    userAttrMapperConfig2.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, ATTRIBUTE_TO_MAP_NAME_2);
    userAttrMapperConfig2.put(OIDCAttributeMapperHelper.JSON_TYPE, ProviderConfigProperty.STRING_TYPE);
    userAttrMapperConfig2.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true");
    userAttrMapperConfig2.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    userAttrMapperConfig2.put(OIDCAttributeMapperHelper.INCLUDE_IN_USERINFO, "true");
    userAttrMapperConfig2.put(ProtocolMapperUtils.MULTIVALUED, "true");

    ProtocolMapperRepresentation hardcodedJsonClaim = new ProtocolMapperRepresentation();
    hardcodedJsonClaim.setName("json-mapper");
    hardcodedJsonClaim.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    hardcodedJsonClaim.setProtocolMapper(HardcodedClaim.PROVIDER_ID);

    Map<String, String> hardcodedJsonClaimMapperConfig = hardcodedJsonClaim.getConfig();
    hardcodedJsonClaimMapperConfig.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, KcOidcBrokerConfiguration.USER_INFO_CLAIM);
    hardcodedJsonClaimMapperConfig.put(OIDCAttributeMapperHelper.JSON_TYPE, "JSON");
    hardcodedJsonClaimMapperConfig.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true");
    hardcodedJsonClaimMapperConfig.put(HardcodedClaim.CLAIM_VALUE, "{\"" + HARDOCDED_CLAIM + "\": \"" + HARDOCDED_VALUE + "\"}");

    client.setProtocolMappers(Arrays.asList(emailMapper, userAttrMapper, userAttrMapper2, nestedAttrMapper, dottedAttrMapper, hardcodedJsonClaim));

    return Collections.singletonList(client);
}
 
Example #17
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example #18
Source File: PairwiseSubCollectorOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

    HttpRequest httpRequest = keycloakSession.getContext().getContextObject(HttpRequest.class);
    MultivaluedMap<String, String> formParams = httpRequest.getDecodedFormParameters();
    String targetUserId = formParams.getFirst("targetUserId");
    String clients = formParams.getFirst("targetClients");

    if (targetUserId == null || clients == null) {
        return;
    }

    Map<String, String> config = mappingModel.getConfig();

    String originalUserSubKey = DEFAULT_ORIGINAL_USER_SUB_KEY;
    String pairwiseSubMapperName = DEFAULT_PAIRWISE_SUB_MAPPER_NAME;
    if (config != null) {
        originalUserSubKey = config.getOrDefault(ORIGINAL_USER_SUB_KEY, originalUserSubKey);
        pairwiseSubMapperName = config.getOrDefault(PAIRWISE_SUB_MAPPER_NAME, pairwiseSubMapperName);
    }

    Map<String, Object> data = new HashMap<>();

    SHA256PairwiseSubMapper subMapper = new SHA256PairwiseSubMapper();

    data.put(originalUserSubKey, targetUserId);

    for (String clientId : clients.split(" ")) {
        ClientModel client = keycloakSession.getContext().getRealm().getClientByClientId(clientId);
        if (client == null) {
            continue;
        }
        ProtocolMapperModel mapperModel = client.getProtocolMapperByName("openid-connect", pairwiseSubMapperName);
        if (mapperModel == null) {
            continue;
        }
        String clientSub = subMapper.generateSub(mapperModel, mapperModel.getConfig().get(PairwiseSubMapperHelper.SECTOR_IDENTIFIER_URI), targetUserId);
        data.put(clientId, clientSub);
    }


    JsonNode claimValue;
    try {
        claimValue = JsonSerialization.createObjectNode(data);
    } catch (IOException ioe) {
        log.warnf("Could not convert object to jsonNode.", ioe);
        return;
    }

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #19
Source File: CrossRealmClientAuthMapper.java    From keycloak-extension-playground with Apache License 2.0 3 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

    Object claimValue = "42";

    fetchCrossRealmData(keycloakSession);

    LOGGER.infof("setClaim %s=%s", mappingModel.getName(), claimValue);

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #20
Source File: RemoteOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 3 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

    Object claimValue = fetchRemoteClaims(mappingModel, userSession, keycloakSession);

    LOGGER.infof("setClaim %s=%s", mappingModel.getName(), claimValue);

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #21
Source File: LdapQueryOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 3 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

    Object claimValue = fetchLdapClaims(mappingModel, userSession, keycloakSession);

    LOGGER.infof("setClaim %s=%s", mappingModel.getName(), claimValue);

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #22
Source File: OpenshiftSAClientAdapter.java    From keycloak with Apache License 2.0 3 votes vote down vote up
private static Set<ProtocolMapperModel> createDefaultProtocolMappers() {
    Set<ProtocolMapperModel> mappers = new HashSet<>();

    ProtocolMapperModel mapper = OIDCAttributeMapperHelper.createClaimMapper("username", "username", "preferred_username", "string", true, true, UserPropertyMapper.PROVIDER_ID);

    mapper.setId(KeycloakModelUtils.generateId());

    mappers.add(mapper);

    return mappers;
}