Java Code Examples for org.keycloak.models.ClientModel#getRole()
The following examples show how to use
org.keycloak.models.ClientModel#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: MigrateTo3_0_0.java From keycloak with Apache License 2.0 | 6 votes |
protected void migrateRealm(RealmModel realm) { realm.getClients().stream() .filter(clientModel -> defaultClients.contains(clientModel.getId())) .filter(clientModel -> Objects.isNull(clientModel.getProtocol())) .forEach(clientModel -> clientModel.setProtocol("openid-connect")); ClientModel client = realm.getClientByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID); if (client == null) return; RoleModel linkRole = client.getRole(MANAGE_ACCOUNT_LINKS); if (linkRole == null) { client.addRole(MANAGE_ACCOUNT_LINKS); } RoleModel manageAccount = client.getRole(MANAGE_ACCOUNT); if (manageAccount == null) return; RoleModel manageAccountLinks = client.getRole(MANAGE_ACCOUNT_LINKS); manageAccount.addCompositeRole(manageAccountLinks); }
Example 2
Source File: MigrateTo1_2_0.java From keycloak with Apache License 2.0 | 6 votes |
public void setupBrokerService(RealmModel realm) { ClientModel client = realm.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID); if (client == null) { client = KeycloakModelUtils.createClient(realm, Constants.BROKER_SERVICE_CLIENT_ID); client.setEnabled(true); client.setName("${client_" + Constants.BROKER_SERVICE_CLIENT_ID + "}"); client.setFullScopeAllowed(false); for (String role : Constants.BROKER_SERVICE_ROLES) { RoleModel roleModel = client.getRole(role); if (roleModel != null) continue; roleModel = client.addRole(role); roleModel.setDescription("${role_" + role.toLowerCase().replaceAll("_", "-") + "}"); } } }
Example 3
Source File: RealmManager.java From keycloak with Apache License 2.0 | 6 votes |
private void checkRealmAdminManagementRoles(RealmModel realm) { if (realm.getName().equals(Config.getAdminRealm())) { return; } // don't need to do this for master realm String realmAdminClientId = getRealmAdminClientId(realm); ClientModel realmAdminClient = realm.getClientByClientId(realmAdminClientId); RoleModel adminRole = realmAdminClient.getRole(AdminRoles.REALM_ADMIN); // if realm-admin role isn't in the realm model, create it if (adminRole == null) { adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN); adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}"); } for (String r : AdminRoles.ALL_REALM_ROLES) { RoleModel found = realmAdminClient.getRole(r); if (found == null) { addAndSetAdminRole(r, realmAdminClient, adminRole); } } addQueryCompositeRoles(realmAdminClient); }
Example 4
Source File: RealmManager.java From keycloak with Apache License 2.0 | 5 votes |
public void addQueryCompositeRoles(ClientModel realmAccess) { RoleModel queryClients = realmAccess.getRole(AdminRoles.QUERY_CLIENTS); RoleModel queryUsers = realmAccess.getRole(AdminRoles.QUERY_USERS); RoleModel queryGroups = realmAccess.getRole(AdminRoles.QUERY_GROUPS); RoleModel viewClients = realmAccess.getRole(AdminRoles.VIEW_CLIENTS); viewClients.addCompositeRole(queryClients); RoleModel viewUsers = realmAccess.getRole(AdminRoles.VIEW_USERS); viewUsers.addCompositeRole(queryUsers); viewUsers.addCompositeRole(queryGroups); }
Example 5
Source File: UserModelIdentity.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean hasClientRole(String clientId, String roleName) { ClientModel client = realm.getClientByClientId(clientId); RoleModel role = client.getRole(roleName); if (role == null) return false; return user.hasRole(role); }
Example 6
Source File: AdminAuth.java From keycloak with Apache License 2.0 | 5 votes |
public boolean hasAppRole(ClientModel app, String role) { if (client instanceof ClientModel) { RoleModel roleModel = app.getRole(role); if (roleModel == null) return false; return user.hasRole(roleModel) && client.hasScope(roleModel); } else { AccessToken.Access access = token.getResourceAccess(app.getClientId()); return access != null && access.isUserInRole(role); } }
Example 7
Source File: RealmsAdminResource.java From keycloak with Apache License 2.0 | 5 votes |
private void grantPermissionsToRealmCreator(RealmModel realm) { if (auth.hasRealmRole(AdminRoles.ADMIN)) { return; } RealmModel adminRealm = new RealmManager(session).getKeycloakAdminstrationRealm(); ClientModel realmAdminApp = realm.getMasterAdminClient(); for (String r : AdminRoles.ALL_REALM_ROLES) { RoleModel role = realmAdminApp.getRole(r); auth.getUser().grantRole(role); } }
Example 8
Source File: UserCommands.java From keycloak with Apache License 2.0 | 5 votes |
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 9
Source File: RealmManager.java From keycloak with Apache License 2.0 | 5 votes |
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 10
Source File: BrokerRunOnServerUtil.java From keycloak with Apache License 2.0 | 5 votes |
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 11
Source File: ClientRolesPartialImport.java From keycloak with Apache License 2.0 | 5 votes |
public void deleteRole(RealmModel realm, String clientId, RoleRepresentation roleRep) { ClientModel client = realm.getClientByClientId(clientId); if (client == null) { // client might have been removed as part of this partial import return; } RoleModel role = client.getRole(getName(roleRep)); if (role == null) { // role might not exist if client was just created as part of the // partial import return; } client.removeRole(role); }
Example 12
Source File: IllegalAdminUpgradeTest.java From keycloak with Apache License 2.0 | 5 votes |
public static void setupUsers(KeycloakSession session) { RealmModel realm = session.realms().getRealmByName(TEST); RealmModel master = session.realms().getRealmByName("master"); ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); ClientModel realmMasterAdminClient = realm.getMasterAdminClient(); RoleModel realmManageUsers = realmAdminClient.getRole(AdminRoles.MANAGE_USERS); RoleModel masterManageUsers = realmMasterAdminClient.getRole(AdminRoles.MANAGE_USERS); RoleModel masterMasterManageUSers = master.getMasterAdminClient().getRole(AdminRoles.MANAGE_USERS); UserModel realmUser = session.users().addUser(realm, "userAdmin"); realmUser.grantRole(realmManageUsers); realmUser.setEnabled(true); session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password")); UserModel masterUser = session.users().addUser(master, "userAdmin"); masterUser.grantRole(masterManageUsers); masterUser.setEnabled(true); session.userCredentialManager().updateCredential(master, masterUser, UserCredentialModel.password("password")); UserModel masterAdmin = session.users().addUser(master, "masterAdmin"); masterAdmin.grantRole(masterMasterManageUSers); masterAdmin.setEnabled(true); session.userCredentialManager().updateCredential(master, masterAdmin, UserCredentialModel.password("password")); UserModel user = session.users().addUser(master, "user"); user.grantRole(masterManageUsers); user.setEnabled(true); session.userCredentialManager().updateCredential(master, user, UserCredentialModel.password("password")); user = session.users().addUser(realm, "user"); user.grantRole(realmManageUsers); user.setEnabled(true); session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); }
Example 13
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 5 votes |
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 14
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 5 votes |
public static void createFederatedClientRoleMappings(UserFederatedStorageProvider federatedStorage, RealmModel realm, ClientModel clientModel, UserRepresentation userRep, List<String> roleNames) { if (userRep == 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()); } federatedStorage.grantRole(realm, userRep.getId(), role); } }
Example 15
Source File: RepresentationToModel.java From keycloak with Apache License 2.0 | 5 votes |
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: RepresentationToModel.java From keycloak with Apache License 2.0 | 5 votes |
public static void createClientScopeMappings(RealmModel realm, ClientModel clientModel, List<ScopeMappingRepresentation> mappings) { for (ScopeMappingRepresentation mapping : mappings) { ScopeContainerModel scopeContainer = getScopeContainerHavingScope(realm, mapping); for (String roleString : mapping.getRoles()) { RoleModel role = clientModel.getRole(roleString.trim()); if (role == null) { role = clientModel.addRole(roleString.trim()); } scopeContainer.addScopeMapping(role); } } }
Example 17
Source File: ClientModelIdentity.java From keycloak with Apache License 2.0 | 5 votes |
@Override public boolean hasClientRole(String clientId, String roleName) { if (serviceAccount == null) return false; ClientModel client = realm.getClientByClientId(clientId); RoleModel role = client.getRole(roleName); if (role == null) return false; return serviceAccount.hasRole(role); }
Example 18
Source File: RealmManager.java From keycloak with Apache License 2.0 | 4 votes |
private void setupAccountManagement(RealmModel realm) { ClientModel accountClient = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID); if (accountClient == null) { accountClient = KeycloakModelUtils.createClient(realm, Constants.ACCOUNT_MANAGEMENT_CLIENT_ID); accountClient.setName("${client_" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "}"); accountClient.setEnabled(true); accountClient.setAlwaysDisplayInConsole(false); accountClient.setFullScopeAllowed(false); accountClient.setRootUrl(Constants.AUTH_BASE_URL_PROP); String baseUrl = "/realms/" + realm.getName() + "/account/"; accountClient.setBaseUrl(baseUrl); accountClient.addRedirectUri(baseUrl + "*"); accountClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); for (String role : AccountRoles.ALL) { accountClient.addDefaultRole(role); RoleModel roleModel = accountClient.getRole(role); roleModel.setDescription("${role_" + role + "}"); } RoleModel manageAccountLinks = accountClient.addRole(AccountRoles.MANAGE_ACCOUNT_LINKS); manageAccountLinks.setDescription("${role_" + AccountRoles.MANAGE_ACCOUNT_LINKS + "}"); RoleModel manageAccount = accountClient.getRole(AccountRoles.MANAGE_ACCOUNT); manageAccount.addCompositeRole(manageAccountLinks); RoleModel viewAppRole = accountClient.addRole(AccountRoles.VIEW_APPLICATIONS); viewAppRole.setDescription("${role_" + AccountRoles.VIEW_APPLICATIONS + "}"); RoleModel viewConsentRole = accountClient.addRole(AccountRoles.VIEW_CONSENT); viewConsentRole.setDescription("${role_" + AccountRoles.VIEW_CONSENT + "}"); RoleModel manageConsentRole = accountClient.addRole(AccountRoles.MANAGE_CONSENT); manageConsentRole.setDescription("${role_" + AccountRoles.MANAGE_CONSENT + "}"); manageConsentRole.addCompositeRole(viewConsentRole); ClientModel accountConsoleClient = realm.getClientByClientId(Constants.ACCOUNT_CONSOLE_CLIENT_ID); if (accountConsoleClient == null) { accountConsoleClient = KeycloakModelUtils.createClient(realm, Constants.ACCOUNT_CONSOLE_CLIENT_ID); accountConsoleClient.setName("${client_" + Constants.ACCOUNT_CONSOLE_CLIENT_ID + "}"); accountConsoleClient.setEnabled(true); accountConsoleClient.setAlwaysDisplayInConsole(false); accountConsoleClient.setFullScopeAllowed(false); accountConsoleClient.setPublicClient(true); accountConsoleClient.setDirectAccessGrantsEnabled(false); accountConsoleClient.setRootUrl(Constants.AUTH_BASE_URL_PROP); accountConsoleClient.setBaseUrl(baseUrl); accountConsoleClient.addRedirectUri(baseUrl + "*"); accountConsoleClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); accountConsoleClient.addScopeMapping(accountClient.getRole(AccountRoles.MANAGE_ACCOUNT)); ProtocolMapperModel audienceMapper = new ProtocolMapperModel(); audienceMapper.setName(OIDCLoginProtocolFactory.AUDIENCE_RESOLVE); audienceMapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); audienceMapper.setProtocolMapper(AudienceResolveProtocolMapper.PROVIDER_ID); accountConsoleClient.addProtocolMapper(audienceMapper); accountConsoleClient.setAttribute(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, "S256"); } } }
Example 19
Source File: RolePolicyProviderFactory.java From keycloak with Apache License 2.0 | 4 votes |
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 20
Source File: IdentityBrokerService.java From keycloak with Apache License 2.0 | 4 votes |
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); } }