Java Code Examples for org.keycloak.models.RealmModel#getRole()

The following examples show how to use org.keycloak.models.RealmModel#getRole() . 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: KeycloakModelUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static RoleModel getRoleFromString(RealmModel realm, String roleName) {
    // Check client roles for all possible splits by dot
    int scopeIndex = roleName.lastIndexOf('.');
    while (scopeIndex >= 0) {
        String appName = roleName.substring(0, scopeIndex);
        ClientModel client = realm.getClientByClientId(appName);
        if (client != null) {
            String role = roleName.substring(scopeIndex + 1);
            return client.getRole(role);
        }

        scopeIndex = roleName.lastIndexOf('.', scopeIndex - 1);
    }

    // determine if roleName is a realm role
    return realm.getRole(roleName);
}
 
Example 2
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 3
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createFederatedRoleMappings(UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, 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());
            }
            federatedStorage.grantRole(realm, userRep.getId(), 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());
            }
            createFederatedClientRoleMappings(federatedStorage, realm, client, userRep, entry.getValue());
        }
    }
}
 
Example 4
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void invokeDelete(KeycloakSession session)  {
    RealmModel realm = session.realms().getRealmByName(TEST);
    AdminPermissionManagement management = AdminPermissions.management(session, realm);
    List<Resource> byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(5, byResourceServer.size());
    RoleModel removedRole = realm.getRole("removedRole");
    realm.removeRole(removedRole);
    ClientModel client = realm.getClientByClientId("removedClient");
    RoleModel removedClientRole = client.getRole("removedClientRole");
    client.removeRole(removedClientRole);
    GroupModel group = KeycloakModelUtils.findGroupByPath(realm, "removedGroup");
    realm.removeGroup(group);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(2, byResourceServer.size());
    realm.removeClient(client.getId());
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(1, byResourceServer.size());
    management.users().setPermissionsEnabled(false);
    Resource userResource = management.authz().getStoreFactory().getResourceStore().findByName("Users", management.realmResourceServer().getId());
    Assert.assertNull(userResource);
    byResourceServer = management.authz().getStoreFactory().getResourceStore().findByResourceServer(management.realmResourceServer().getId());
    Assert.assertEquals(0, byResourceServer.size());
}
 
Example 5
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 6
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 7
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static RoleModel setupOfflineRole(RealmModel realm) {
    RoleModel offlineRole = realm.getRole(Constants.OFFLINE_ACCESS_ROLE);

    if (offlineRole == null) {
        offlineRole = realm.addRole(Constants.OFFLINE_ACCESS_ROLE);
        offlineRole.setDescription("${role_offline-access}");
        realm.addDefaultRole(Constants.OFFLINE_ACCESS_ROLE);
    }

    return offlineRole;
}
 
Example 8
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupAuthorizationServices(RealmModel realm) {
    for (String roleName : Constants.AUTHZ_DEFAULT_AUTHORIZATION_ROLES) {
        if (realm.getRole(roleName) == null) {
            RoleModel role = realm.addRole(roleName);
            role.setDescription("${role_" + roleName + "}");
            realm.addDefaultRole(roleName);
        }
    }
}
 
Example 9
Source File: CompositeRolesModelTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static RoleModel getRole(RealmModel realm, String appName, String roleName) {
    if ("realm".equals(appName)) {
        return realm.getRole(roleName);
    } else {
        return realm.getClientByClientId(appName).getRole(roleName);
    }
}
 
Example 10
Source File: UserCommands.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Set<RoleModel> findRoles(RealmModel realm, String rolesList) {
    Set<RoleModel> result = new HashSet<>();

    String[] roles = rolesList.split(",");
    for (String roleName : roles) {
        roleName = roleName.trim();
        RoleModel role;
        if (roleName.contains("/")) {
            String[] spl = roleName.split("/");
            ClientModel client = realm.getClientByClientId(spl[0]);
            if (client == null) {
                log.errorf("Client not found: %s", spl[0]);
                throw new HandledException();
            }
            role = client.getRole(spl[1]);
        } else {
            role = realm.getRole(roleName);
        }

        if (role == null) {
            log.errorf("Role not found: %s", roleName);
            throw new HandledException();
        }

        result.add(role);
    }

    return result;
}
 
Example 11
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void createMasterAdminManagement(RealmModel realm) {
    RealmModel adminRealm;
    RoleModel adminRole;

    if (realm.getName().equals(Config.getAdminRealm())) {
        adminRealm = realm;

        adminRole = realm.addRole(AdminRoles.ADMIN);

        RoleModel createRealmRole = realm.addRole(AdminRoles.CREATE_REALM);
        adminRole.addCompositeRole(createRealmRole);
        createRealmRole.setDescription("${role_" + AdminRoles.CREATE_REALM + "}");
    } else {
        adminRealm = model.getRealm(Config.getAdminRealm());
        adminRole = adminRealm.getRole(AdminRoles.ADMIN);
    }
    adminRole.setDescription("${role_"+AdminRoles.ADMIN+"}");

    ClientModel realmAdminApp = KeycloakModelUtils.createClient(adminRealm, KeycloakModelUtils.getMasterRealmAdminApplicationClientId(realm.getName()));
    // No localized name for now
    realmAdminApp.setName(realm.getName() + " Realm");
    realmAdminApp.setBearerOnly(true);
    realm.setMasterAdminClient(realmAdminApp);

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        RoleModel role = realmAdminApp.addRole(r);
        role.setDescription("${role_"+r+"}");
        adminRole.addCompositeRole(role);
    }
    addQueryCompositeRoles(realmAdminApp);
}
 
Example 12
Source File: RealmManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void checkMasterAdminManagementRoles(RealmModel realm) {
    RealmModel adminRealm = model.getRealmByName(Config.getAdminRealm());
    RoleModel adminRole = adminRealm.getRole(AdminRoles.ADMIN);

    ClientModel masterAdminClient = realm.getMasterAdminClient();
    for (String r : AdminRoles.ALL_REALM_ROLES) {
        RoleModel found = masterAdminClient.getRole(r);
        if (found == null) {
            addAndSetAdminRole(r, masterAdminClient, adminRole);
        }
    }
    addQueryCompositeRoles(masterAdminClient);
}
 
Example 13
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 14
Source File: RolePolicyProviderFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void updateRoles(Policy policy, AuthorizationProvider authorization, Set<RolePolicyRepresentation.RoleDefinition> roles) {
    RealmModel realm = authorization.getRealm();
    Set<RolePolicyRepresentation.RoleDefinition> updatedRoles = new HashSet<>();

    if (roles != null) {
        for (RolePolicyRepresentation.RoleDefinition definition : roles) {
            String roleName = definition.getId();
            String clientId = null;
            int clientIdSeparator = roleName.indexOf("/");

            if (clientIdSeparator != -1) {
                clientId = roleName.substring(0, clientIdSeparator);
                roleName = roleName.substring(clientIdSeparator + 1);
            }

            RoleModel role;

            if (clientId == null) {
                role = realm.getRole(roleName);

                if (role == null) {
                    role = realm.getRoleById(roleName);
                }
            } else {
                ClientModel client = realm.getClientByClientId(clientId);

                if (client == null) {
                    throw new RuntimeException("Client with id [" + clientId + "] not found.");
                }

                role = client.getRole(roleName);
            }

            // fallback to find any client role with the given name
            if (role == null) {
                String finalRoleName = roleName;
                role = realm.getClients().stream().map(clientModel -> clientModel.getRole(finalRoleName)).filter(roleModel -> roleModel != null)
                        .findFirst().orElse(null);
            }

            if (role == null) {
                throw new RuntimeException("Error while updating policy [" + policy.getName()  + "]. Role [" + roleName + "] could not be found.");
            }

            definition.setId(role.getId());

            updatedRoles.add(definition);
        }
    }

    try {
        policy.putConfig("roles", JsonSerialization.writeValueAsString(updatedRoles));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to serialize roles", cause);
    }
}
 
Example 15
Source File: OIDCLoginProtocolFactory.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void createDefaultClientScopesImpl(RealmModel newRealm) {
    //name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, and updated_at.
    ClientScopeModel profileScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PROFILE);
    profileScope.setDescription("OpenID Connect built-in scope: profile");
    profileScope.setDisplayOnConsentScreen(true);
    profileScope.setConsentScreenText(PROFILE_SCOPE_CONSENT_TEXT);
    profileScope.setIncludeInTokenScope(true);
    profileScope.setProtocol(getId());
    profileScope.addProtocolMapper(builtins.get(FULL_NAME));
    profileScope.addProtocolMapper(builtins.get(FAMILY_NAME));
    profileScope.addProtocolMapper(builtins.get(GIVEN_NAME));
    profileScope.addProtocolMapper(builtins.get(MIDDLE_NAME));
    profileScope.addProtocolMapper(builtins.get(NICKNAME));
    profileScope.addProtocolMapper(builtins.get(USERNAME));
    profileScope.addProtocolMapper(builtins.get(PROFILE_CLAIM));
    profileScope.addProtocolMapper(builtins.get(PICTURE));
    profileScope.addProtocolMapper(builtins.get(WEBSITE));
    profileScope.addProtocolMapper(builtins.get(GENDER));
    profileScope.addProtocolMapper(builtins.get(BIRTHDATE));
    profileScope.addProtocolMapper(builtins.get(ZONEINFO));
    profileScope.addProtocolMapper(builtins.get(LOCALE));
    profileScope.addProtocolMapper(builtins.get(UPDATED_AT));

    ClientScopeModel emailScope = newRealm.addClientScope(OAuth2Constants.SCOPE_EMAIL);
    emailScope.setDescription("OpenID Connect built-in scope: email");
    emailScope.setDisplayOnConsentScreen(true);
    emailScope.setConsentScreenText(EMAIL_SCOPE_CONSENT_TEXT);
    emailScope.setIncludeInTokenScope(true);
    emailScope.setProtocol(getId());
    emailScope.addProtocolMapper(builtins.get(EMAIL));
    emailScope.addProtocolMapper(builtins.get(EMAIL_VERIFIED));

    ClientScopeModel addressScope = newRealm.addClientScope(OAuth2Constants.SCOPE_ADDRESS);
    addressScope.setDescription("OpenID Connect built-in scope: address");
    addressScope.setDisplayOnConsentScreen(true);
    addressScope.setConsentScreenText(ADDRESS_SCOPE_CONSENT_TEXT);
    addressScope.setIncludeInTokenScope(true);
    addressScope.setProtocol(getId());
    addressScope.addProtocolMapper(builtins.get(ADDRESS));

    ClientScopeModel phoneScope = newRealm.addClientScope(OAuth2Constants.SCOPE_PHONE);
    phoneScope.setDescription("OpenID Connect built-in scope: phone");
    phoneScope.setDisplayOnConsentScreen(true);
    phoneScope.setConsentScreenText(PHONE_SCOPE_CONSENT_TEXT);
    phoneScope.setIncludeInTokenScope(true);
    phoneScope.setProtocol(getId());
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER));
    phoneScope.addProtocolMapper(builtins.get(PHONE_NUMBER_VERIFIED));

    // 'profile' and 'email' will be default scopes for now. 'address' and 'phone' will be optional scopes
    newRealm.addDefaultClientScope(profileScope, true);
    newRealm.addDefaultClientScope(emailScope, true);
    newRealm.addDefaultClientScope(addressScope, false);
    newRealm.addDefaultClientScope(phoneScope, false);

    RoleModel offlineRole = newRealm.getRole(OAuth2Constants.OFFLINE_ACCESS);
    if (offlineRole != null) {
        ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(newRealm, OAuth2Constants.OFFLINE_ACCESS);
        if (offlineAccessScope == null) {
            DefaultClientScopes.createOfflineAccessClientScope(newRealm, offlineRole);
        }
    }

    addRolesClientScope(newRealm);
    addWebOriginsClientScope(newRealm);
    addMicroprofileJWTClientScope(newRealm);
}
 
Example 16
Source File: RealmRolesPartialImport.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void remove(RealmModel realm, KeycloakSession session, RoleRepresentation roleRep) {
    RoleModel role = realm.getRole(getName(roleRep));
    RoleHelper helper = new RoleHelper(realm);
    helper.deleteRole(role);
}