private BrokerLinkEntity getBrokerLinkEntity(RealmModel realm, String userId, String socialProvider) { TypedQuery<BrokerLinkEntity> query = em.createNamedQuery("findBrokerLinkByUserAndProvider", BrokerLinkEntity.class) .setParameter("userId", userId) .setParameter("realmId", realm.getId()) .setParameter("identityProvider", socialProvider); List<BrokerLinkEntity> results = query.getResultList(); return results.size() > 0 ? results.get(0) : null; }
public CachedRealm(Long revision, RealmModel model) { super(revision, model.getId()); name = model.getName(); displayName = model.getDisplayName(); displayNameHtml = model.getDisplayNameHtml(); enabled = model.isEnabled(); allowUserManagedAccess = model.isUserManagedAccessAllowed(); sslRequired = model.getSslRequired(); registrationAllowed = model.isRegistrationAllowed(); registrationEmailAsUsername = model.isRegistrationEmailAsUsername(); rememberMe = model.isRememberMe(); verifyEmail = model.isVerifyEmail(); loginWithEmailAllowed = model.isLoginWithEmailAllowed(); duplicateEmailsAllowed = model.isDuplicateEmailsAllowed(); resetPasswordAllowed = model.isResetPasswordAllowed(); identityFederationEnabled = model.isIdentityFederationEnabled(); editUsernameAllowed = model.isEditUsernameAllowed(); bruteForceProtected = model.isBruteForceProtected(); permanentLockout = model.isPermanentLockout(); maxFailureWaitSeconds = model.getMaxFailureWaitSeconds(); minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds(); waitIncrementSeconds = model.getWaitIncrementSeconds(); quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds(); maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds(); failureFactor = model.getFailureFactor(); defaultSignatureAlgorithm = model.getDefaultSignatureAlgorithm(); revokeRefreshToken = model.isRevokeRefreshToken(); refreshTokenMaxReuse = model.getRefreshTokenMaxReuse();
public void migrate(KeycloakSession session) { List<RealmModel> realms = session.realms().getRealms(); for (RealmModel realm : realms) { DefaultAuthenticationFlows.migrateFlows(realm); // add reset credentials flo realm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY); realm.setBrowserFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.BROWSER_FLOW)); realm.setRegistrationFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.REGISTRATION_FLOW)); realm.setDirectGrantFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.DIRECT_GRANT_FLOW)); AuthenticationFlowModel resetFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW); if (resetFlow == null) { DefaultAuthenticationFlows.resetCredentialsFlow(realm); } else { realm.setResetCredentialsFlow(resetFlow); } AuthenticationFlowModel clientAuthFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW); if (clientAuthFlow == null) { DefaultAuthenticationFlows.clientAuthFlow(realm); } else { realm.setClientAuthenticationFlow(clientAuthFlow); } for (ClientModel client : realm.getClients()) { client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType()); } } } }
private String getRealmName() { if (realm.getDisplayName() != null) { return realm.getDisplayName(); } else { return ObjectUtil.capitalize(realm.getName()); } }
public static Set<RoleModel> getDefaultRoles(RealmModel realm) { Set<RoleModel> set = new HashSet<>(); for (String r : realm.getDefaultRoles()) { set.add(realm.getRole(r)); } for (ClientModel application : realm.getClients()) { for (String r : application.getDefaultRoles()) { set.add(application.getRole(r)); } } return set; } public static void addDefaultRoles(RealmModel realm, UserModel userModel) {
@GET @Path("/get-user-by-service-account-client") @Produces(MediaType.APPLICATION_JSON) public UserRepresentation getUserByServiceAccountClient(@QueryParam("realmName") String realmName, @QueryParam("clientId") String clientId) { RealmModel realm = getRealmByName(realmName); ClientModel client = realm.getClientByClientId(clientId); UserModel user = session.users().getServiceAccount(client); if (user == null) return null; return ModelToRepresentation.toRepresentation(user); }
@PUT @Path("{clientId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateOIDC(@PathParam("clientId") String clientId, OIDCClientRepresentationExtended clientOIDC) { try { ClientRepresentation client = DescriptionConverterExt.toInternal(session, clientOIDC); OIDCClientRegistrationContext oidcContext = new OIDCClientRegistrationContext(session, client, this, clientOIDC); client = update(clientId, oidcContext); ClientModel clientModel = session.getContext().getRealm().getClientByClientId(client.getClientId()); updatePairwiseSubMappers(clientModel, SubjectType.parse(clientOIDC.getSubjectType()), clientOIDC.getSectorIdentifierUri()); updateClientRepWithProtocolMappers(clientModel, client); URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(client.getClientId()).build(); OIDCClientRepresentationExtended clientOIDCResponse = DescriptionConverterExt.toExternalResponse(session, client, uri); return Response.ok(clientOIDCResponse).build(); } catch (ClientRegistrationException cre) { ServicesLogger.LOGGER.clientRegistrationException(cre.getMessage()); throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client metadata invalid", Response.Status.BAD_REQUEST); } }
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createOIDC(OIDCClientRepresentationExtended clientOIDC) { if (clientOIDC.getClientId() != null) { client = create(oidcContext); ClientModel clientModel = session.getContext().getRealm().getClientByClientId(client.getClientId()); updatePairwiseSubMappers(clientModel, SubjectType.parse(clientOIDC.getSubjectType()), clientOIDC.getSectorIdentifierUri()); updateClientRepWithProtocolMappers(clientModel, client); URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(client.getClientId()).build(); OIDCClientRepresentationExtended clientOIDCResponse = DescriptionConverterExt.toExternalResponse(session, client, uri); clientOIDCResponse.setClientIdIssuedAt(Time.currentTime());
beer.setRealmId(realm.getId()); beer.setName(rep.getName()); beer.setType(rep.getType()); em.persist(beer); em.flush(); .success(); if (session.getTransactionManager().isActive()) { session.getTransactionManager().commit(); return Response.created(uriInfo.getAbsolutePathBuilder().path(beer.getId()).build()).build(); if (session.getTransactionManager().isActive()) { session.getTransactionManager().setRollbackOnly();
@Override public List<UserModel> searchForUser(Map<String, String> attributes, RealmModel realm, int firstResult, int maxResults) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<UserEntity> queryBuilder = builder.createQuery(UserEntity.class); Root<UserEntity> root = queryBuilder.from(UserEntity.class); predicates.add(builder.equal(root.get("realmId"), realm.getId())); if (!session.getAttributeOrDefault(UserModel.INCLUDE_SERVICE_ACCOUNT, true)) { predicates.add(root.get("serviceAccountClientLink").isNull()); Set<String> userGroups = (Set<String>) session.getAttribute(UserModel.GROUPS); TypedQuery<UserEntity> query = em.createQuery(queryBuilder); query.setFirstResult(firstResult); query.setMaxResults(maxResults); UserProvider users = session.users(); for (UserEntity entity : query.getResultList()) { results.add(users.getUserById(entity.getId(), realm));
@Override public List<String> getMembership(RealmModel realm, GroupModel group, int firstResult, int max) { TypedQuery<String> query = em.createNamedQuery("fedgroupMembership", String.class) .setParameter("realmId", realm.getId()) .setParameter("groupId", group.getId()); query.setFirstResult(firstResult); query.setMaxResults(max); return query.getResultList(); }
session.getKeycloakSessionFactory().publish(event); session.users().preRemove(realm, group); realm.removeDefaultGroup(group); for (GroupModel subGroup : group.getSubGroups()) { session.realms().removeGroup(realm, subGroup); GroupEntity groupEntity = em.find(GroupEntity.class, group.getId()); if ((groupEntity == null) || (!groupEntity.getRealm().getId().equals(realm.getId()))) { return false; em.createNamedQuery("deleteGroupRoleMappingsByGroup").setParameter("group", groupEntity).executeUpdate(); RealmEntity realmEntity = em.getReference(RealmEntity.class, realm.getId()); realmEntity.getGroups().remove(groupEntity);
@Override public boolean removeRole(RealmModel realm, RoleModel role) { session.users().preRemove(realm, role); RoleContainerModel container = role.getContainer(); if (container.getDefaultRoles().contains(role.getName())) { container.removeDefaultRoles(role.getName()); } RoleEntity roleEntity = em.getReference(RoleEntity.class, role.getId()); String compositeRoleTable = JpaUtils.getTableNameForNativeQuery("COMPOSITE_ROLE", em); em.createNativeQuery("delete from " + compositeRoleTable + " where CHILD_ROLE = :role").setParameter("role", roleEntity).executeUpdate(); realm.getClients().forEach(c -> c.deleteScopeMapping(role)); em.createNamedQuery("deleteClientScopeRoleMappingByRole").setParameter("role", roleEntity).executeUpdate(); int val = em.createNamedQuery("deleteGroupRoleMappingsByRole").setParameter("roleId", roleEntity.getId()).executeUpdate(); em.flush(); em.remove(roleEntity); session.getKeycloakSessionFactory().publish(new RoleContainerModel.RoleRemovedEvent() { @Override public RoleModel getRole() { return role; } @Override public KeycloakSession getKeycloakSession() { return session; } }); em.flush(); return true; }
public AccountFederatedIdentityBean(KeycloakSession session, RealmModel realm, UserModel user, URI baseUri, String stateChecker) { this.session = session; URI accountIdentityUpdateUri = Urls.accountFederatedIdentityUpdate(baseUri, realm.getName()); List<IdentityProviderModel> identityProviders = realm.getIdentityProviders(); Set<FederatedIdentityModel> identities = session.users().getFederatedIdentities(user, realm); Set<FederatedIdentityEntry> orderedSet = new TreeSet<>(IdentityProviderComparator.INSTANCE); int availableIdentities = 0; if (identityProviders != null && !identityProviders.isEmpty()) { for (IdentityProviderModel provider : identityProviders) { String providerId = provider.getAlias(); FederatedIdentityModel identity = getIdentity(identities, providerId); if (identity != null) { availableIdentities++; } String action = identity != null ? "remove" : "add"; String actionUrl = UriBuilder.fromUri(accountIdentityUpdateUri) .queryParam("action", action) .queryParam("provider_id", providerId) .queryParam("stateChecker", stateChecker) .build().toString(); FederatedIdentityEntry entry = new FederatedIdentityEntry(identity, provider.getAlias(), provider.getAlias(), actionUrl, provider.getConfig() != null ? provider.getConfig().get("guiOrder") : null); orderedSet.add(entry); } } this.identities = new LinkedList<FederatedIdentityEntry>(orderedSet); // Removing last social provider is not possible if you don't have other possibility to authenticate this.removeLinkPossible = availableIdentities > 1 || user.getFederationLink() != null || AccountService.isPasswordSet(user); }
if (client == null) return false; session.users().preRemove(realm, client); session.getKeycloakSessionFactory().publish(new RealmModel.ClientRemovedEvent() { @Override public ClientModel getClient() { int countRemoved = em.createNamedQuery("deleteClientScopeClientMappingByClient") .setParameter("client", clientEntity) .executeUpdate(); em.remove(clientEntity); // i have no idea why, but this needs to come before deleteScopeMapping em.flush(); } catch (RuntimeException e) { logger.errorv("Unable to delete client entity: {0} from realm {1}", client.getClientId(), realm.getName()); throw e;
@Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel identity) { FederatedIdentityEntity entity = new FederatedIdentityEntity(); entity.setRealmId(realm.getId()); entity.setIdentityProvider(identity.getIdentityProvider()); entity.setUserId(identity.getUserId()); entity.setUserName(identity.getUserName().toLowerCase()); entity.setToken(identity.getToken()); UserEntity userEntity = em.getReference(UserEntity.class, user.getId()); entity.setUser(userEntity); em.persist(entity); em.flush(); }
@Override public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) { if (id == null) { id = KeycloakModelUtils.generateId(); } UserEntity entity = new UserEntity(); entity.setId(id); entity.setCreatedTimestamp(System.currentTimeMillis()); entity.setUsername(username.toLowerCase()); entity.setRealmId(realm.getId()); em.persist(entity); em.flush(); UserAdapter userModel = new UserAdapter(session, realm, em, entity); if (addDefaultRoles) { DefaultRoles.addDefaultRoles(realm, userModel); for (GroupModel g : realm.getDefaultGroups()) { userModel.joinGroupImpl(g); // No need to check if user has group as it's new user } } if (addDefaultRequiredActions){ for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) { if (r.isEnabled() && r.isDefaultAction()) { userModel.addRequiredAction(r.getAlias()); } } } return userModel; }
public CachedRealm(RealmCache cache, RealmProvider delegate, RealmModel model) { id = model.getId(); name = model.getName(); displayName = model.getDisplayName(); displayNameHtml = model.getDisplayNameHtml(); enabled = model.isEnabled(); sslRequired = model.getSslRequired(); registrationAllowed = model.isRegistrationAllowed(); registrationEmailAsUsername = model.isRegistrationEmailAsUsername(); rememberMe = model.isRememberMe(); verifyEmail = model.isVerifyEmail(); resetPasswordAllowed = model.isResetPasswordAllowed(); identityFederationEnabled = model.isIdentityFederationEnabled(); editUsernameAllowed = model.isEditUsernameAllowed(); bruteForceProtected = model.isBruteForceProtected(); maxFailureWaitSeconds = model.getMaxFailureWaitSeconds(); minimumQuickLoginWaitSeconds = model.getMinimumQuickLoginWaitSeconds(); waitIncrementSeconds = model.getWaitIncrementSeconds(); quickLoginCheckMilliSeconds = model.getQuickLoginCheckMilliSeconds(); maxDeltaTimeSeconds = model.getMaxDeltaTimeSeconds(); failureFactor = model.getFailureFactor(); revokeRefreshToken = model.isRevokeRefreshToken(); ssoSessionIdleTimeout = model.getSsoSessionIdleTimeout(); ssoSessionMaxLifespan = model.getSsoSessionMaxLifespan(); offlineSessionIdleTimeout = model.getOfflineSessionIdleTimeout(); accessTokenLifespan = model.getAccessTokenLifespan(); accessTokenLifespanForImplicitFlow = model.getAccessTokenLifespanForImplicitFlow(); accessCodeLifespan = model.getAccessCodeLifespan();