Java Code Examples for org.keycloak.models.UserModel#grantRole()

The following examples show how to use org.keycloak.models.UserModel#grantRole() . 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: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createRoleMappings(UserRepresentation userRep, UserModel user, RealmModel realm) {
    if (userRep.getRealmRoles() != null) {
        for (String roleString : userRep.getRealmRoles()) {
            RoleModel role = realm.getRole(roleString.trim());
            if (role == null) {
                role = realm.addRole(roleString.trim());
            }
            user.grantRole(role);
        }
    }
    if (userRep.getClientRoles() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
            ClientModel client = realm.getClientByClientId(entry.getKey());
            if (client == null) {
                throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
            }
            createClientRoleMappings(client, user, entry.getValue());
        }
    }
}
 
Example 2
Source File: ApplianceBootstrap.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void createMasterRealmUser(String username, String password) {
    RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
    session.getContext().setRealm(realm);

    if (session.users().getUsersCount(realm) > 0) {
        throw new IllegalStateException("Can't create initial user as users already exists");
    }

    UserModel adminUser = session.users().addUser(realm, username);
    adminUser.setEnabled(true);

    UserCredentialModel usrCredModel = UserCredentialModel.password(password);
    session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel);

    RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
    adminUser.grantRole(adminRole);
}
 
Example 3
Source File: UserCommands.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void createUsersInBatch(KeycloakSession session, int first, int count) {
    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Unknown realm: %s", realmName);
        throw new HandledException();
    }

    Set<RoleModel> roles = findRoles(realm, roleNames);

    int last = first + count;
    for (int counter = first; counter < last; counter++) {
        String username = usernamePrefix + counter;
        UserModel user = session.users().addUser(realm, username);
        user.setEnabled(true);
        user.setEmail(username + "@keycloak.org");
        UserCredentialModel passwordCred = UserCredentialModel.password(password);
        session.userCredentialManager().updateCredential(realm, user, passwordCred);

        for (RoleModel role : roles) {
            user.grantRole(role);
        }
    }
    log.infof("Users from %s to %s created", usernamePrefix + first, usernamePrefix + (last - 1));
}
 
Example 4
Source File: BrokerRunOnServerUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
static RunOnServer grantReadTokenRole(String username) {
    return session -> {
        RealmModel realm = session.getContext().getRealm();
        ClientModel brokerClient = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
        RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
        UserModel user = session.users().getUserByUsername(username, realm);
        user.grantRole(readTokenRole);
    };
}
 
Example 5
Source File: AdvancedClaimToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
    if (role == null) {
        throw new IdentityBrokerException("Unable to find role: " + roleName);
    }
    if (!hasAllClaimValues(mapperModel, context)) {
        user.deleteRoleMapping(role);
    } else {
        user.grantRole(role);
    }
}
 
Example 6
Source File: AdvancedClaimToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    if (hasAllClaimValues(mapperModel, context)) {
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
        if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
        user.grantRole(role);
    }
}
 
Example 7
Source File: ClaimToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    if (hasClaimValue(mapperModel, context)) {
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
        if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
        user.grantRole(role);
    }
}
 
Example 8
Source File: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private UserModel createUserModel(RealmModel realm, String rawUsername) throws NotFoundException {

        String username = rawUsername.toLowerCase().trim();
        FederatedUserModel remoteUser = federatedUserService.getUserDetails(username);
        LOG.infof("Creating user model for: %s", username);
        UserModel userModel = session.userStorage().addUser(realm, username);

        if (!username.equals(remoteUser.getEmail())) {
            throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", username, remoteUser.getUsername()));
        }

        userModel.setFederationLink(model.getId());
        userModel.setEnabled(remoteUser.isEnabled());
        userModel.setEmail(username);
        userModel.setEmailVerified(remoteUser.isEmailVerified());
        userModel.setFirstName(remoteUser.getFirstName());
        userModel.setLastName(remoteUser.getLastName());

        if (remoteUser.getAttributes() != null) {
            Map<String, List<String>> attributes = remoteUser.getAttributes();
            for (String attributeName : attributes.keySet())
                userModel.setAttribute(attributeName, attributes.get(attributeName));
        }

        if (remoteUser.getRoles() != null) {
            for (String role : remoteUser.getRoles()) {
                RoleModel roleModel = realm.getRole(role);
                if (roleModel != null) {
                    userModel.grantRole(roleModel);
                    LOG.infof("Granted user %s, role %s", username, role);
                }
            }
        }

        return userModel;
    }
 
Example 9
Source File: ExternalKeycloakRoleToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    if (hasRole(realm, mapperModel, context)) {
        user.grantRole(searchRole(realm, mapperModel));
    } else {
        user.deleteRoleMapping(searchRole(realm, mapperModel));
    }
}
 
Example 10
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void addDirectExchanger(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.addRole("example");
    AdminPermissionManagement management = AdminPermissions.management(session, realm);

    ClientModel directExchanger = realm.addClient("direct-exchanger");
    directExchanger.setName("direct-exchanger");
    directExchanger.setClientId("direct-exchanger");
    directExchanger.setPublicClient(false);
    directExchanger.setDirectAccessGrantsEnabled(true);
    directExchanger.setEnabled(true);
    directExchanger.setSecret("secret");
    directExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directExchanger.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_SIGNED_AND_ENCRYPTED_TARGET), true);
    management.clients().setPermissionsEnabled(realm.getClientByClientId(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET), true);

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonatorsDirect");
    clientImpersonateRep.addClient(directExchanger.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
    impersonatedUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password"));
    impersonatedUser.grantRole(exampleRole);
}
 
Example 11
Source File: AttributeToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
    if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
    if (!isAttributePresent(mapperModel, context)) {
        user.deleteRoleMapping(role);
    }else{
        user.grantRole(role);
    }

}
 
Example 12
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setup5152(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName(TEST);
    ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
    RoleModel realmAdminRole = realmAdminClient.getRole(AdminRoles.REALM_ADMIN);

    UserModel realmUser = session.users().addUser(realm, "realm-admin");
    realmUser.grantRole(realmAdminRole);
    realmUser.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password"));
}
 
Example 13
Source File: AttributeToRoleMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    if (isAttributePresent(mapperModel, context)) {
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
        if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
        user.grantRole(role);
    }
}
 
Example 14
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ResourceServer createResourceServer(ClientModel client, KeycloakSession session, boolean addDefaultRoles) {
    if ((client.isBearerOnly() || client.isPublicClient())
            && !(client.getClientId().equals(Config.getAdminRealm() + "-realm") || client.getClientId().equals(Constants.REALM_MANAGEMENT_CLIENT_ID))) {
        throw new RuntimeException("Only confidential clients are allowed to set authorization settings");
    }
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    UserModel serviceAccount = session.users().getServiceAccount(client);

    if (serviceAccount == null) {
        client.setServiceAccountsEnabled(true);
    }

    if (addDefaultRoles) {
        RoleModel umaProtectionRole = client.getRole(Constants.AUTHZ_UMA_PROTECTION);

        if (umaProtectionRole == null) {
            umaProtectionRole = client.addRole(Constants.AUTHZ_UMA_PROTECTION);
        }

        if (serviceAccount != null) {
            serviceAccount.grantRole(umaProtectionRole);
        }
    }

    ResourceServerRepresentation representation = new ResourceServerRepresentation();

    representation.setAllowRemoteResourceManagement(true);
    representation.setClientId(client.getId());

    return toModel(representation, authorization);
}
 
Example 15
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void createClientRoleMappings(ClientModel clientModel, UserModel user, List<String> roleNames) {
    if (user == null) {
        throw new RuntimeException("User not found");
    }

    for (String roleName : roleNames) {
        RoleModel role = clientModel.getRole(roleName.trim());
        if (role == null) {
            role = clientModel.addRole(roleName.trim());
        }
        user.grantRole(role);

    }
}
 
Example 16
Source File: ClientTokenExchangeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void setupRealm(KeycloakSession session) {
    addDirectExchanger(session);

    RealmModel realm = session.realms().getRealmByName(TEST);
    RoleModel exampleRole = realm.getRole("example");

    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    ClientModel target = realm.getClientByClientId("target");
    assertNotNull(target);

    RoleModel impersonateRole = management.getRealmManagementClient().getRole(ImpersonationConstants.IMPERSONATION_ROLE);

    ClientModel clientExchanger = realm.addClient("client-exchanger");
    clientExchanger.setClientId("client-exchanger");
    clientExchanger.setPublicClient(false);
    clientExchanger.setDirectAccessGrantsEnabled(true);
    clientExchanger.setEnabled(true);
    clientExchanger.setSecret("secret");
    clientExchanger.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    clientExchanger.setFullScopeAllowed(false);
    clientExchanger.addScopeMapping(impersonateRole);
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_ID));
    clientExchanger.addProtocolMapper(UserSessionNoteMapper.createUserSessionNoteMapper(IMPERSONATOR_USERNAME));

    ClientModel illegal = realm.addClient("illegal");
    illegal.setClientId("illegal");
    illegal.setPublicClient(false);
    illegal.setDirectAccessGrantsEnabled(true);
    illegal.setEnabled(true);
    illegal.setSecret("secret");
    illegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    illegal.setFullScopeAllowed(false);

    ClientModel legal = realm.addClient("legal");
    legal.setClientId("legal");
    legal.setPublicClient(false);
    legal.setDirectAccessGrantsEnabled(true);
    legal.setEnabled(true);
    legal.setSecret("secret");
    legal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    legal.setFullScopeAllowed(false);

    ClientModel directLegal = realm.addClient("direct-legal");
    directLegal.setClientId("direct-legal");
    directLegal.setPublicClient(false);
    directLegal.setDirectAccessGrantsEnabled(true);
    directLegal.setEnabled(true);
    directLegal.setSecret("secret");
    directLegal.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directLegal.setFullScopeAllowed(false);

    ClientModel directPublic = realm.addClient("direct-public");
    directPublic.setClientId("direct-public");
    directPublic.setPublicClient(true);
    directPublic.setDirectAccessGrantsEnabled(true);
    directPublic.setEnabled(true);
    directPublic.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directPublic.setFullScopeAllowed(false);

    ClientModel directNoSecret = realm.addClient("direct-no-secret");
    directNoSecret.setClientId("direct-no-secret");
    directNoSecret.setPublicClient(false);
    directNoSecret.setDirectAccessGrantsEnabled(true);
    directNoSecret.setEnabled(true);
    directNoSecret.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    directNoSecret.setFullScopeAllowed(false);

    // permission for client to client exchange to "target" client
    ClientPolicyRepresentation clientRep = new ClientPolicyRepresentation();
    clientRep.setName("to");
    clientRep.addClient(clientExchanger.getId());
    clientRep.addClient(legal.getId());
    clientRep.addClient(directLegal.getId());

    ResourceServer server = management.realmResourceServer();
    Policy clientPolicy = management.authz().getStoreFactory().getPolicyStore().create(clientRep, server);
    management.clients().exchangeToPermission(target).addAssociatedPolicy(clientPolicy);

    // permission for user impersonation for a client

    ClientPolicyRepresentation clientImpersonateRep = new ClientPolicyRepresentation();
    clientImpersonateRep.setName("clientImpersonators");
    clientImpersonateRep.addClient(directLegal.getId());
    clientImpersonateRep.addClient(directPublic.getId());
    clientImpersonateRep.addClient(directNoSecret.getId());
    server = management.realmResourceServer();
    Policy clientImpersonatePolicy = management.authz().getStoreFactory().getPolicyStore().create(clientImpersonateRep, server);
    management.users().setPermissionsEnabled(true);
    management.users().adminImpersonatingPermission().addAssociatedPolicy(clientImpersonatePolicy);
    management.users().adminImpersonatingPermission().setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);

    UserModel user = session.users().addUser(realm, "user");
    user.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
    user.grantRole(exampleRole);
    user.grantRole(impersonateRole);

    UserModel bad = session.users().addUser(realm, "bad-impersonator");
    bad.setEnabled(true);
    session.userCredentialManager().updateCredential(realm, bad, UserCredentialModel.password("password"));
}
 
Example 17
Source File: DefaultRoles.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void addDefaultRoles(RealmModel realm, UserModel userModel) {
    for (RoleModel role : getDefaultRoles(realm)) {
        userModel.grantRole(role);
    }
}
 
Example 18
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response afterFirstBrokerLogin(ClientSessionCode<AuthenticationSessionModel> clientSessionCode) {
    AuthenticationSessionModel authSession = clientSessionCode.getClientSession();
    try {
        this.event.detail(Details.CODE_ID, authSession.getParentSession().getId())
                .removeDetail("auth_method");

        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authSession);
        String providerId = context.getIdpConfig().getAlias();

        event.detail(Details.IDENTITY_PROVIDER, providerId);
        event.detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

        // Ensure the first-broker-login flow was successfully finished
        String authProvider = authSession.getAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS);
        if (authProvider == null || !authProvider.equals(providerId)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that first-broker-login flow was finished");
        }

        // firstBrokerLogin workflow finished. Removing note now
        authSession.removeAuthNote(AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);

        UserModel federatedUser = authSession.getAuthenticatedUser();
        if (federatedUser == null) {
            throw new IdentityBrokerException("Couldn't found authenticated federatedUser in authentication session");
        }

        event.user(federatedUser);
        event.detail(Details.USERNAME, federatedUser.getUsername());

        if (context.getIdpConfig().isAddReadTokenRoleOnCreate()) {
            ClientModel brokerClient = realmModel.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
            if (brokerClient == null) {
                throw new IdentityBrokerException("Client 'broker' not available. Maybe realm has not migrated to support the broker token exchange service");
            }
            RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
            federatedUser.grantRole(readTokenRole);
        }

        // Add federated identity link here
        FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(),
                context.getUsername(), context.getToken());
        session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);


        String isRegisteredNewUser = authSession.getAuthNote(AbstractIdpAuthenticator.BROKER_REGISTERED_NEW_USER);
        if (Boolean.parseBoolean(isRegisteredNewUser)) {

            logger.debugf("Registered new user '%s' after first login with identity provider '%s'. Identity provider username is '%s' . ", federatedUser.getUsername(), providerId, context.getUsername());

            context.getIdp().importNewUser(session, realmModel, federatedUser, context);
            Set<IdentityProviderMapperModel> mappers = realmModel.getIdentityProviderMappersByAlias(providerId);
            if (mappers != null) {
                KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
                for (IdentityProviderMapperModel mapper : mappers) {
                    IdentityProviderMapper target = (IdentityProviderMapper)sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
                    target.importNewUser(session, realmModel, federatedUser, mapper, context);
                }
            }

            if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(federatedUser.getEmail()) && !Boolean.parseBoolean(authSession.getAuthNote(AbstractIdpAuthenticator.UPDATE_PROFILE_EMAIL_CHANGED))) {
                logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", federatedUser.getUsername(), context.getIdpConfig().getAlias());
                federatedUser.setEmailVerified(true);
            }

            event.event(EventType.REGISTER)
                    .detail(Details.REGISTER_METHOD, "broker")
                    .detail(Details.EMAIL, federatedUser.getEmail())
                    .success();

        } else {
            logger.debugf("Linked existing keycloak user '%s' with identity provider '%s' . Identity provider username is '%s' .", federatedUser.getUsername(), providerId, context.getUsername());

            event.event(EventType.FEDERATED_IDENTITY_LINK)
                    .success();

            updateFederatedIdentity(context, federatedUser);
        }

        return finishOrRedirectToPostBrokerLogin(authSession, context, true, clientSessionCode);

    }  catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}
 
Example 19
Source File: HardcodedRoleMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void grantUserRole(RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel) {
    String roleName = mapperModel.getConfig().get(ConfigConstants.ROLE);
    RoleModel role = KeycloakModelUtils.getRoleFromString(realm, roleName);
    if (role == null) throw new IdentityBrokerException("Unable to find role: " + roleName);
    user.grantRole(role);
}
 
Example 20
Source File: ExternalKeycloakRoleToRoleMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void importNewUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    if (hasRole(realm, mapperModel, context)) {
        user.grantRole(searchRole(realm, mapperModel));
    }
}