Refine search
public CachedUser(RealmModel realm, UserModel user) { this.id = user.getId(); this.realm = realm.getId(); this.username = user.getUsername(); this.createdTimestamp = user.getCreatedTimestamp(); this.firstName = user.getFirstName(); this.lastName = user.getLastName(); this.attributes.putAll(user.getAttributes()); this.email = user.getEmail(); this.emailVerified = user.isEmailVerified(); this.credentials.addAll(user.getCredentialsDirectly()); this.enabled = user.isEnabled(); this.totp = user.isOtpEnabled(); this.federationLink = user.getFederationLink(); this.serviceAccountClientLink = user.getServiceAccountClientLink(); this.requiredActions.addAll(user.getRequiredActions()); for (RoleModel role : user.getRoleMappings()) { roleMappings.add(role.getId()); } Set<GroupModel> groupMappings = user.getGroups(); if (groupMappings != null) { for (GroupModel group : groupMappings) { groups.add(group.getId()); } } }
public boolean isValid(RealmModel realm, UserModel local) { // KerberosUsernamePasswordAuthenticator.isUserAvailable is an overhead, so avoid it for now String kerberosPrincipal = local.getUsername() + "@" + kerberosConfig.getKerberosRealm(); return kerberosPrincipal.equalsIgnoreCase(local.getFirstAttribute(KERBEROS_PRINCIPAL)); }
private void migrateUsers(KeycloakSession session, RealmModel realm) { List<UserModel> users = session.userStorage().getUsers(realm, false); for (UserModel user : users) { String email = user.getEmail(); email = KeycloakModelUtils.toLowerCaseSafe(email); if (email != null && !email.equals(user.getEmail())) { user.setEmail(email); } } } }
@Override public void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCt) { UserModel user = userSession.getUser(); String first = user.getFirstName() == null ? "" : user.getFirstName() + " "; String last = user.getLastName() == null ? "" : user.getLastName(); setMappedAttribute(attributes, mappingModel, first + last); }
public AccountBean(UserModel user, MultivaluedMap<String, String> profileFormData) { this.user = user; this.profileFormData = profileFormData; for (Map.Entry<String, List<String>> attr : user.getAttributes().entrySet()) { List<String> attrValue = attr.getValue(); if (attrValue.size() > 0) { attributes.put(attr.getKey(), attrValue.get(0)); } if (attrValue.size() > 1) { logger.warnf("There are more values for attribute '%s' of user '%s' . Will display just first value", attr.getKey(), user.getUsername()); } } if (profileFormData != null) { for (String key : profileFormData.keySet()) { if (key.startsWith("user.attributes.")) { String attribute = key.substring("user.attributes.".length()); attributes.put(attribute, profileFormData.getFirst(key)); } } } }
@POST @Consumes("text/xml;charset=utf-8") @Produces("text/xml;charset=utf-8") public Response validate(String input) { MultivaluedMap<String, String> queryParams = request.getUri().getQueryParameters(); try { String soapAction = Optional.ofNullable(request.getHttpHeaders().getHeaderString("SOAPAction")).map(s -> s.trim().replace("\"", "")).orElse(""); if (!soapAction.equals("http://www.oasis-open.org/committees/security")) { throw new CASValidationException(CASErrorCode.INTERNAL_ERROR, "Not a validation request", Response.Status.BAD_REQUEST); } String service = queryParams.getFirst(TARGET_PARAM); boolean renew = queryParams.containsKey(CASLoginProtocol.RENEW_PARAM); checkRealm(); checkSsl(); checkClient(service); String issuer = Urls.realmIssuer(request.getUri().getBaseUri(), realm.getName()); String ticket = getTicket(input); checkTicket(ticket, renew); UserModel user = clientSession.getUserSession().getUser(); Map<String, Object> attributes = getUserAttributes(); SAML11ResponseType response = SamlResponseHelper.successResponse(issuer, user.getUsername(), attributes); return Response.ok(SamlResponseHelper.soap(response)).build(); } catch (CASValidationException ex) { logger.warnf("Invalid SAML1.1 token %s", ex.getErrorDescription()); SAML11ResponseType response = SamlResponseHelper.errorResponse(ex); return Response.ok().entity(SamlResponseHelper.soap(response)).build(); } }
public String getUsername() { return profileFormData != null ? profileFormData.getFirst("username") : user.getUsername(); }
public String getLastName() { return profileFormData != null ? profileFormData.getFirst("lastName") :user.getLastName(); }
public String getFirstName() { return profileFormData != null ? profileFormData.getFirst("firstName") : user.getFirstName(); }
public static UserRepresentation toRepresentation(UserModel user) { UserRepresentation rep = new UserRepresentation(); rep.setId(user.getId()); rep.setUsername(user.getUsername()); rep.setCreatedTimestamp(user.getCreatedTimestamp()); rep.setLastName(user.getLastName()); rep.setFirstName(user.getFirstName()); rep.setEmail(user.getEmail()); rep.setEnabled(user.isEnabled()); rep.setEmailVerified(user.isEmailVerified()); rep.setTotp(user.isOtpEnabled()); rep.setFederationLink(user.getFederationLink()); List<String> reqActions = new ArrayList<String>(); Set<String> requiredActions = user.getRequiredActions(); for (String ra : requiredActions){ reqActions.add(ra); } rep.setRequiredActions(reqActions); if (user.getAttributes() != null && !user.getAttributes().isEmpty()) { Map<String, Object> attrs = new HashMap<>(); attrs.putAll(user.getAttributes()); rep.setAttributes(attrs); } return rep; }
protected void deleteInvalidUser(RealmModel realm, UserModel user) { KeycloakSession tx = session.getKeycloakSessionFactory().create(); try { tx.getTransaction().begin(); RealmModel realmModel = tx.realms().getRealm(realm.getId()); if (realmModel == null) return; UserModel deletedUser = tx.userStorage().getUserById(user.getId(), realmModel); tx.userStorage().removeUser(realmModel, deletedUser); logger.debugf("Removed invalid user '%s'", user.getUsername()); tx.getTransaction().commit(); } finally { tx.close(); } }
AuthInfo (Event event, KeycloakSession keycloakSession) { fields = new String[] { event.getDetails() != null ? event.getDetails().get("username") : keycloakSession.users().getUserById(event.getUserId(), keycloakSession.getContext().getRealm()) .getUsername(), event.getIpAddress() }; } AuthInfo(String s) {
@Override public void evict(RealmModel realm, UserModel user) { if (!transactionActive) throw new IllegalStateException("Cannot call evict() without a transaction"); getDelegate(); // invalidations need delegate set if (user instanceof CachedUserModel) { ((CachedUserModel)user).invalidate(); } else { cache.userUpdatedInvalidations(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), invalidations); invalidationEvents.add(UserUpdatedEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId())); } }
@Override public void onUserRemoved(RealmModel realm, UserModel user) { removeUserSessions(realm, user); em.createNamedQuery("removeLoginFailuresByUser").setParameter("realmId", realm.getId()).setParameter("username", user.getUsername()).setParameter("email", user.getEmail()).executeUpdate(); }
keycloakSession.getTransactionManager().begin(); try { final RealmModel realm = keycloakSession.realms().getRealmByName(hostname); if (realm == null) { LOG.info("Realm " + hostname + " not found"); ClientModel clientModel = realm.getClientByClientId(token.getIssuedFor()); } else { authenticated = true; authenticatedUser = new UserDataImpl(user.getId(), user.getUsername(), user.getGroups().stream().map(GroupModel::getName).collect(Collectors.toSet())); keycloakSession.getTransactionManager().commit(); keycloakSession.close();
/** * Called after successful authentication * * @param realm realm * @param username username without realm prefix * @return user if found or successfully created. Null if user with same username already exists, but is not linked to this provider */ protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) { UserModel user = session.userLocalStorage().getUserByUsername(username, realm); if (user != null) { user = session.users().getUserById(user.getId(), realm); // make sure we get a cached instance logger.debug("Kerberos authenticated user " + username + " found in Keycloak storage"); if (!model.getId().equals(user.getFederationLink())) { logger.warn("User with username " + username + " already exists, but is not linked to provider [" + model.getName() + "]"); return null; } else { UserModel proxied = validate(realm, user); if (proxied != null) { return proxied; } else { logger.warn("User with username " + username + " already exists and is linked to provider [" + model.getName() + "] but kerberos principal is not correct. Kerberos principal on user is: " + user.getFirstAttribute(KERBEROS_PRINCIPAL)); logger.warn("Will re-create user"); new UserManager(session).removeUser(realm, user, session.userLocalStorage()); } } } logger.debug("Kerberos authenticated user " + username + " not in Keycloak storage. Creating him"); return importUserToKeycloak(realm, username); }
List<UserModel> userModels = realm.getUsers(); for (UserModel userModel : userModels) { UserEntity userEntity = new UserEntity(); userEntity.setId(userModel.getId()); result.add(userEntity); userEntity.setLoginName(userModel.getLoginName()); userEntity.setRealmId(realm.getId()); AuthenticationLinkModel authLink = userModel.getAuthenticationLink(); if (authLink != null) { AuthenticationLinkEntity authLinkEntity = new AuthenticationLinkEntity(); Set<UserModel.RequiredAction> requiredActions = userModel.getRequiredActions(); if (requiredActions != null && !requiredActions.isEmpty()) { userEntity.setRequiredActions(new ArrayList<UserModel.RequiredAction>(requiredActions)); userEntity.setAttributes(userModel.getAttributes()); Set<RoleModel> roles = userModel.getRoleMappings(); List<String> roleIds = new ArrayList<String>(); for (RoleModel role : roles) { List<UserCredentialValueModel> credentials = userModel.getCredentialsDirectly(); List<CredentialEntity> credEntities = new ArrayList<CredentialEntity>(); for (UserCredentialValueModel credModel : credentials) {
Set<FederatedIdentityModel> socialLinks = session.users().getFederatedIdentities(user, realm); List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<FederatedIdentityRepresentation>(); for (FederatedIdentityModel socialLink : socialLinks) { Set<RoleModel> roles = user.getRoleMappings(); List<String> realmRoleNames = new ArrayList<>(); Map<String, List<String>> clientRoleNames = new HashMap<>(); List<UserCredentialValueModel> creds = user.getCredentialsDirectly(); List<CredentialRepresentation> credReps = new ArrayList<CredentialRepresentation>(); for (UserCredentialValueModel cred : creds) { userRep.setFederationLink(user.getFederationLink()); List<UserConsentModel> consents = user.getConsents(); LinkedList<UserConsentRepresentation> consentReps = new LinkedList<UserConsentRepresentation>(); for (UserConsentModel consent : consents) { if (user.getServiceAccountClientLink() != null) { String clientInternalId = user.getServiceAccountClientLink(); ClientModel client = realm.getClientById(clientInternalId); if (client != null) { userRep.setServiceAccountClientId(client.getClientId()); for (GroupModel group : user.getGroups()) { groups.add(ModelToRepresentation.buildGroupPath(group));
protected AuthUser createAuthenticatedUserInstance(UserModel user) { return new AuthUser(user.getId(), user.getLoginName(), getName()) .setName(user.getFirstName(), user.getLastName()) .setEmail(user.getEmail()); } }