Search in sources :

Example 21 with UserModel

use of org.keycloak.models.UserModel in project keycloak by keycloak.

the class ClientTokenExchangeSAML2Test method addDirectExchanger.

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);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Policy(org.keycloak.authorization.model.Policy) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) RoleModel(org.keycloak.models.RoleModel) ResourceServer(org.keycloak.authorization.model.ResourceServer) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement)

Example 22 with UserModel

use of org.keycloak.models.UserModel in project keycloak by keycloak.

the class KerberosFederationProvider method importUserToKeycloak.

protected UserModel importUserToKeycloak(RealmModel realm, String username) {
    // Just guessing email from kerberos realm
    String email = username + "@" + kerberosConfig.getKerberosRealm().toLowerCase();
    logger.debugf("Creating kerberos user: %s, email: %s to local Keycloak storage", username, email);
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEnabled(true);
    user.setEmail(email);
    user.setFederationLink(model.getId());
    user.setSingleAttribute(KERBEROS_PRINCIPAL, username + "@" + kerberosConfig.getKerberosRealm());
    if (kerberosConfig.isUpdateProfileFirstLogin()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
    }
    return validate(realm, user);
}
Also used : UserModel(org.keycloak.models.UserModel)

Example 23 with UserModel

use of org.keycloak.models.UserModel in project keycloak by keycloak.

the class InfinispanUserSessionProvider method getUserSessionsStream.

protected Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserSessionPredicate predicate, boolean offline) {
    if (offline && loadOfflineSessionsFromDatabase) {
        // fetch the offline user-sessions from the persistence provider
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        if (predicate.getUserId() != null) {
            UserModel user = session.users().getUserById(realm, predicate.getUserId());
            if (user != null) {
                return persister.loadUserSessionsStream(realm, user, true, 0, null);
            }
        }
        if (predicate.getBrokerUserId() != null) {
            String[] idpAliasSessionId = predicate.getBrokerUserId().split("\\.");
            Map<String, String> attributes = new HashMap<>();
            attributes.put(UserModel.IDP_ALIAS, idpAliasSessionId[0]);
            attributes.put(UserModel.IDP_USER_ID, idpAliasSessionId[1]);
            UserProvider userProvider = session.getProvider(UserProvider.class);
            UserModel userModel = userProvider.searchForUserStream(realm, attributes, 0, null).findFirst().orElse(null);
            return userModel != null ? persister.loadUserSessionsStream(realm, userModel, true, 0, null) : Stream.empty();
        }
        if (predicate.getBrokerSessionId() != null) {
            // currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way
            throw new ModelException("Dynamic database lookup for offline user-sessions by broker session ID is currently only supported for preloaded sessions. " + "Set preloadOfflineSessionsFromDatabase option to \"true\" in " + UserSessionSpi.NAME + " SPI in " + InfinispanUserSessionProviderFactory.PROVIDER_ID + " provider to enable the lookup.");
        }
    }
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
    cache = CacheDecorators.skipCacheLoaders(cache);
    // and then mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
    return StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false).map(Mappers.userSessionEntity()).map(entity -> this.wrap(realm, entity, offline));
}
Also used : UserModel(org.keycloak.models.UserModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ModelException(org.keycloak.models.ModelException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserProvider(org.keycloak.models.UserProvider) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 24 with UserModel

use of org.keycloak.models.UserModel in project keycloak by keycloak.

the class UserCacheSession method getUserByUsername.

@Override
public UserModel getUserByUsername(RealmModel realm, String username) {
    logger.tracev("getUserByUsername: {0}", username);
    username = username.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        logger.tracev("realmInvalidations");
        return getDelegate().getUserByUsername(realm, username);
    }
    String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
    if (invalidations.contains(cacheKey)) {
        logger.tracev("invalidations");
        return getDelegate().getUserByUsername(realm, username);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);
    String userId = null;
    if (query == null) {
        logger.tracev("query null");
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByUsername(realm, username);
        if (model == null) {
            logger.tracev("model from delegate null");
            return null;
        }
        userId = model.getId();
        if (invalidations.contains(userId))
            return model;
        if (managedUsers.containsKey(userId)) {
            logger.tracev("return managed user");
            return managedUsers.get(userId);
        }
        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            // this was cached, so we can cache query too
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            logger.tracev("invalidated cache return delegate");
            return getDelegate().getUserByUsername(realm, username);
        }
        logger.trace("return getUserById");
        return getUserById(realm, userId);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserListQuery(org.keycloak.models.cache.infinispan.entities.UserListQuery)

Example 25 with UserModel

use of org.keycloak.models.UserModel in project keycloak by keycloak.

the class UserCacheSession method getUserByEmail.

@Override
public UserModel getUserByEmail(RealmModel realm, String email) {
    if (email == null)
        return null;
    email = email.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        return getDelegate().getUserByEmail(realm, email);
    }
    String cacheKey = getUserByEmailCacheKey(realm.getId(), email);
    if (invalidations.contains(cacheKey)) {
        return getDelegate().getUserByEmail(realm, email);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);
    String userId = null;
    if (query == null) {
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByEmail(realm, email);
        if (model == null)
            return null;
        userId = model.getId();
        if (invalidations.contains(userId))
            return model;
        if (managedUsers.containsKey(userId))
            return managedUsers.get(userId);
        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            return getDelegate().getUserByEmail(realm, email);
        }
        return getUserById(realm, userId);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserListQuery(org.keycloak.models.cache.infinispan.entities.UserListQuery)

Aggregations

UserModel (org.keycloak.models.UserModel)383 RealmModel (org.keycloak.models.RealmModel)220 Test (org.junit.Test)126 ClientModel (org.keycloak.models.ClientModel)86 KeycloakSession (org.keycloak.models.KeycloakSession)81 CachedUserModel (org.keycloak.models.cache.CachedUserModel)52 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)43 List (java.util.List)41 UserSessionModel (org.keycloak.models.UserSessionModel)40 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)40 RoleModel (org.keycloak.models.RoleModel)39 ComponentModel (org.keycloak.component.ComponentModel)31 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)29 Path (javax.ws.rs.Path)28 UserManager (org.keycloak.models.UserManager)28 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)27 Map (java.util.Map)25 GroupModel (org.keycloak.models.GroupModel)24 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)24