Search in sources :

Example 1 with RealmModel

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

the class RolePolicyProviderFactory method postInit.

@Override
public void postInit(KeycloakSessionFactory factory) {
    factory.register(event -> {
        if (event instanceof RoleRemovedEvent) {
            KeycloakSession keycloakSession = ((RoleRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
            StoreFactory storeFactory = provider.getStoreFactory();
            PolicyStore policyStore = storeFactory.getPolicyStore();
            RoleModel removedRole = ((RoleRemovedEvent) event).getRole();
            RoleContainerModel container = removedRole.getContainer();
            ResourceServerStore resourceServerStore = storeFactory.getResourceServerStore();
            if (container instanceof RealmModel) {
                RealmModel realm = (RealmModel) container;
                realm.getClientsStream().forEach(clientModel -> updateResourceServer(clientModel, removedRole, resourceServerStore, policyStore));
            } else {
                ClientModel clientModel = (ClientModel) container;
                updateResourceServer(clientModel, removedRole, resourceServerStore, policyStore);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) KeycloakSession(org.keycloak.models.KeycloakSession) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RoleRemovedEvent(org.keycloak.models.RoleContainerModel.RoleRemovedEvent) PolicyStore(org.keycloak.authorization.store.PolicyStore) RoleModel(org.keycloak.models.RoleModel) StoreFactory(org.keycloak.authorization.store.StoreFactory) RoleContainerModel(org.keycloak.models.RoleContainerModel)

Example 2 with RealmModel

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

the class ClientPolicyProviderFactory method onExport.

@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) {
    ClientPolicyRepresentation userRep = toRepresentation(policy, authorization);
    Map<String, String> config = new HashMap<>();
    try {
        RealmModel realm = authorization.getRealm();
        config.put("clients", JsonSerialization.writeValueAsString(userRep.getClients().stream().map(id -> realm.getClientById(id).getClientId()).collect(Collectors.toList())));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause);
    }
    representation.setConfig(config);
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) Arrays(java.util.Arrays) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) Config(org.keycloak.Config) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) PolicyProviderFactory(org.keycloak.authorization.policy.provider.PolicyProviderFactory) RealmModel(org.keycloak.models.RealmModel) Set(java.util.Set) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) PolicyStore(org.keycloak.authorization.store.PolicyStore) ClientRemovedEvent(org.keycloak.models.ClientModel.ClientRemovedEvent) Collectors(java.util.stream.Collectors) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) List(java.util.List) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) HashMap(java.util.HashMap) IOException(java.io.IOException)

Example 3 with RealmModel

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

the class UserPolicyProviderFactory method updateUsers.

private void updateUsers(Policy policy, AuthorizationProvider authorization, Set<String> users) {
    KeycloakSession session = authorization.getKeycloakSession();
    RealmModel realm = authorization.getRealm();
    UserProvider userProvider = session.users();
    Set<String> updatedUsers = new HashSet<>();
    if (users != null) {
        for (String userId : users) {
            UserModel user = null;
            try {
                user = userProvider.getUserByUsername(realm, userId);
            } catch (Exception ignore) {
            }
            if (user == null) {
                user = userProvider.getUserById(realm, userId);
            }
            if (user == null) {
                throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. User [" + userId + "] could not be found.");
            }
            updatedUsers.add(user.getId());
        }
    }
    try {
        policy.putConfig("users", JsonSerialization.writeValueAsString(updatedUsers));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to serialize users", cause);
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserProvider(org.keycloak.models.UserProvider) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 4 with RealmModel

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

the class DefaultAttributes method normalizeAttributes.

/**
 * Normalizes the given {@code attributes} (as they were provided when creating a profile) accordingly to the
 * profile configuration and the current context.
 *
 * @param attributes the denormalized map of attributes
 *
 * @return a normalized map of attributes
 */
private Map<String, List<String>> normalizeAttributes(Map<String, ?> attributes) {
    Map<String, List<String>> newAttributes = new HashMap<>();
    RealmModel realm = session.getContext().getRealm();
    if (attributes != null) {
        for (Map.Entry<String, ?> entry : attributes.entrySet()) {
            String key = entry.getKey();
            if (!isSupportedAttribute(key)) {
                continue;
            }
            if (key.startsWith(Constants.USER_ATTRIBUTES_PREFIX)) {
                key = key.substring(Constants.USER_ATTRIBUTES_PREFIX.length());
            }
            List<String> values;
            Object value = entry.getValue();
            if (value instanceof String) {
                values = Collections.singletonList((String) value);
            } else {
                values = (List<String>) value;
            }
            if (key.equals(UserModel.USERNAME)) {
                values = Collections.singletonList(values.get(0).toLowerCase());
            }
            newAttributes.put(key, Collections.unmodifiableList(values));
        }
    }
    // the profile should always hold all attributes defined in the config
    for (String attributeName : metadataByAttribute.keySet()) {
        if (!isSupportedAttribute(attributeName) || newAttributes.containsKey(attributeName)) {
            continue;
        }
        List<String> values = EMPTY_VALUE;
        AttributeMetadata metadata = metadataByAttribute.get(attributeName);
        if (user != null && isIncludeAttributeIfNotProvided(metadata)) {
            values = user.getAttributes().getOrDefault(attributeName, EMPTY_VALUE);
        }
        newAttributes.put(attributeName, values);
    }
    if (user != null) {
        List<String> username = newAttributes.get(UserModel.USERNAME);
        if (username == null || username.isEmpty() || (!realm.isEditUsernameAllowed() && UserProfileContext.USER_API.equals(context))) {
            newAttributes.put(UserModel.USERNAME, Collections.singletonList(user.getUsername()));
        }
    }
    List<String> email = newAttributes.get(UserModel.EMAIL);
    if (email != null && realm.isRegistrationEmailAsUsername()) {
        final List<String> lowerCaseEmailList = email.stream().filter(Objects::nonNull).map(String::toLowerCase).collect(Collectors.toList());
        newAttributes.put(UserModel.USERNAME, lowerCaseEmailList);
    }
    return newAttributes;
}
Also used : RealmModel(org.keycloak.models.RealmModel) HashMap(java.util.HashMap) Objects(java.util.Objects) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with RealmModel

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

the class AuthenticationProcessor method finishAuthentication.

public Response finishAuthentication(LoginProtocol protocol) {
    RealmModel realm = authenticationSession.getRealm();
    ClientSessionContext clientSessionCtx = attachSession();
    event.success();
    return AuthenticationManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, connection, event, authenticationSession, protocol);
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientSessionContext(org.keycloak.models.ClientSessionContext)

Aggregations

RealmModel (org.keycloak.models.RealmModel)591 Test (org.junit.Test)249 UserModel (org.keycloak.models.UserModel)225 KeycloakSession (org.keycloak.models.KeycloakSession)152 ClientModel (org.keycloak.models.ClientModel)149 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)90 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)84 ComponentModel (org.keycloak.component.ComponentModel)83 RoleModel (org.keycloak.models.RoleModel)73 UserSessionModel (org.keycloak.models.UserSessionModel)64 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)62 List (java.util.List)55 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)51 GroupModel (org.keycloak.models.GroupModel)47 HashMap (java.util.HashMap)38 Collectors (java.util.stream.Collectors)34 CachedUserModel (org.keycloak.models.cache.CachedUserModel)34 Path (javax.ws.rs.Path)30 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)30 Map (java.util.Map)29