Java Code Examples for org.keycloak.models.UserModel#getId()

The following examples show how to use org.keycloak.models.UserModel#getId() . 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: CachedUser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public CachedUser(Long revision, RealmModel realm, UserModel user, int notBefore) {
    super(revision, user.getId());
    this.realm = realm.getId();
    this.username = user.getUsername();
    this.createdTimestamp = user.getCreatedTimestamp();
    this.email = user.getEmail();
    this.emailVerified = user.isEmailVerified();
    this.enabled = user.isEnabled();
    this.federationLink = user.getFederationLink();
    this.serviceAccountClientLink = user.getServiceAccountClientLink();
    this.notBefore = notBefore;
    this.requiredActions = new DefaultLazyLoader<>(UserModel::getRequiredActions, Collections::emptySet);
    this.attributes = new DefaultLazyLoader<>(userModel -> new MultivaluedHashMap<>(userModel.getAttributes()), MultivaluedHashMap::new);
    this.roleMappings = new DefaultLazyLoader<>(userModel -> userModel.getRoleMappings().stream().map(RoleModel::getId).collect(Collectors.toSet()), Collections::emptySet);
    this.groups = new DefaultLazyLoader<>(userModel -> userModel.getGroups().stream().map(GroupModel::getId).collect(Collectors.toCollection(LinkedHashSet::new)), LinkedHashSet::new);
}
 
Example 2
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createLoginCookie(KeycloakSession keycloakSession, RealmModel realm, UserModel user, UserSessionModel session, UriInfo uriInfo, ClientConnection connection) {
    String cookiePath = getIdentityCookiePath(realm, uriInfo);
    String issuer = Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName());
    IdentityCookieToken identityCookieToken = createIdentityToken(keycloakSession, realm, user, session, issuer);
    String encoded = keycloakSession.tokens().encode(identityCookieToken);
    boolean secureOnly = realm.getSslRequired().isRequired(connection);
    int maxAge = NewCookie.DEFAULT_MAX_AGE;
    if (session != null && session.isRememberMe()) {
        maxAge = realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();
    }
    logger.debugv("Create login cookie - name: {0}, path: {1}, max-age: {2}", KEYCLOAK_IDENTITY_COOKIE, cookiePath, maxAge);
    CookieHelper.addCookie(KEYCLOAK_IDENTITY_COOKIE, encoded, cookiePath, null, null, maxAge, secureOnly, true, SameSiteAttributeValue.NONE);
    //builder.cookie(new NewCookie(cookieName, encoded, cookiePath, null, null, maxAge, secureOnly));// todo httponly , true);

    String sessionCookieValue = realm.getName() + "/" + user.getId();
    if (session != null) {
        sessionCookieValue += "/" + session.getId();
    }
    // THIS SHOULD NOT BE A HTTPONLY COOKIE!  It is used for OpenID Connect Iframe Session support!
    // Max age should be set to the max lifespan of the session as it's used to invalidate old-sessions on re-login
    int sessionCookieMaxAge = session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0 ? realm.getSsoSessionMaxLifespanRememberMe() : realm.getSsoSessionMaxLifespan();
    CookieHelper.addCookie(KEYCLOAK_SESSION_COOKIE, sessionCookieValue, cookiePath, null, null, sessionCookieMaxAge, secureOnly, false, SameSiteAttributeValue.NONE);
    P3PHelper.addP3PHeader();
}
 
Example 3
Source File: PolicyEvaluationService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public String getId() {
    if (userSession != null) {
        return super.getId();
    }

    String issuedFor = accessToken.getIssuedFor();

    if (issuedFor != null) {
        UserModel serviceAccount = keycloakSession.users().getServiceAccount(realm.getClientByClientId(issuedFor));

        if (serviceAccount != null) {
            return serviceAccount.getId();
        }
    }

    return null;
}
 
Example 4
Source File: PermissionTicketService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String getUserId(String userIdOrName) {
    UserProvider userProvider = authorization.getKeycloakSession().users();
    RealmModel realm = authorization.getRealm();
    UserModel userModel = userProvider.getUserById(userIdOrName, realm);

    if (userModel != null) {
        return userModel.getId();
    }

    userModel = userProvider.getUserByUsername(userIdOrName, realm);

    if (userModel != null) {
        return userModel.getId();
    }

    return userIdOrName;
}
 
Example 5
Source File: UserStorageManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean removeUser(RealmModel realm, UserModel user) {
    if (getFederatedStorage() != null) getFederatedStorage().preRemove(realm, user);
    StorageId storageId = new StorageId(user.getId());
    if (storageId.getProviderId() == null) {
        boolean linkRemoved = true;
        if (user.getFederationLink() != null) {
            if (isStorageProviderEnabled(realm, user.getFederationLink())) {
                UserStorageProvider provider = getStorageProvider(session, realm, user.getFederationLink());
                if (provider != null && provider instanceof UserRegistrationProvider) {
                    ((UserRegistrationProvider) provider).removeUser(realm, user);
                }
            } else {
                linkRemoved = false;
            }
        }
        return localStorage().removeUser(realm, user) && linkRemoved;
    }
    UserRegistrationProvider registry = (UserRegistrationProvider)getStorageProvider(session, realm, storageId.getProviderId());
    if (registry == null) {
        throw new ModelException("Could not resolve StorageProvider: " + storageId.getProviderId());
    }
    return registry.removeUser(realm, user);

}
 
Example 6
Source File: RemoteOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Object fetchRemoteClaims(ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession) {

        try {
            String remoteUrl = mappingModel.getConfig().getOrDefault(REMOTE_URL_PROPERTY, "http://localhost:7777/claims");
            UserModel user = userSession.getUser();
            String url = remoteUrl + "?userId=" + user.getId() + "&username=" + URLEncoder.encode(user.getUsername(), "UTF-8");
            JsonNode jsonNode = SimpleHttp.doGet(url, keycloakSession).asJson();
            return jsonNode;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example 7
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getUserByEmail(String email, RealmModel realm) {
    if (email == null) return null;
    email = email.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        return getDelegate().getUserByEmail(email, realm);
    }
    String cacheKey = getUserByEmailCacheKey(realm.getId(), email);
    if (invalidations.contains(cacheKey)) {
        return getDelegate().getUserByEmail(email, realm);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);

    String userId = null;
    if (query == null) {
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByEmail(email, realm);
        if (model == null) return null;
        userId = model.getId();
        if (invalidations.contains(userId)) return model;
        if (managedUsers.containsKey(userId)) return managedUsers.get(userId);

        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            return getDelegate().getUserByEmail(email, realm);

        }
        return getUserById(userId, realm);
    }
}
 
Example 8
Source File: DefaultBruteForceProtector.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void failedLogin(RealmModel realm, UserModel user, ClientConnection clientConnection) {
    try {
        FailedLogin event = new FailedLogin(realm.getId(), user.getId(), clientConnection.getRemoteAddr());
        queue.offer(event);
        // wait a minimum of seconds for type to process so that a hacker
        // cannot flood with failed logins and overwhelm the queue and not have notBefore updated to block next requests
        // todo failure HTTP responses should be queued via async HTTP
        event.latch.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    logger.trace("sent failure event");
}
 
Example 9
Source File: DefaultBruteForceProtector.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void successfulLogin(final RealmModel realm, final UserModel user, final ClientConnection clientConnection) {
    try {
        SuccessfulLogin event = new SuccessfulLogin(realm.getId(), user.getId(), clientConnection.getRemoteAddr());
        queue.offer(event);

        event.latch.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }
    logger.trace("sent success event");
}
 
Example 10
Source File: LDAPStorageUserManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void setManagedProxiedUser(UserModel proxiedUser, LDAPObject ldapObject) {
    String userId = proxiedUser.getId();
    ManagedUserEntry entry = managedUsers.get(userId);
    if (entry != null) {
        throw new IllegalStateException("Don't expect to have entry for user " + userId);
    }

    LDAPTransaction ldapTransaction = new LDAPTransaction(provider, ldapObject);
    ManagedUserEntry newEntry = new ManagedUserEntry(proxiedUser, ldapObject, ldapTransaction);
    managedUsers.put(userId, newEntry);
}
 
Example 11
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public UserModel getUserByUsername(String username, RealmModel realm) {
    logger.tracev("getUserByUsername: {0}", username);
    username = username.toLowerCase();
    if (realmInvalidations.contains(realm.getId())) {
        logger.tracev("realmInvalidations");
        return getDelegate().getUserByUsername(username, realm);
    }
    String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
    if (invalidations.contains(cacheKey)) {
        logger.tracev("invalidations");
        return getDelegate().getUserByUsername(username, realm);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);

    String userId = null;
    if (query == null) {
        logger.tracev("query null");
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByUsername(username, realm);
        if (model == null) {
            logger.tracev("model from delegate null");
            return null;
        }
        userId = model.getId();
        if (invalidations.contains(userId)) return model;
        if (managedUsers.containsKey(userId)) {
            logger.tracev("return managed user");
            return managedUsers.get(userId);
        }

        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            logger.tracev("invalidated cache return delegate");
            return getDelegate().getUserByUsername(username, realm);

        }
        logger.trace("return getUserById");
        return getUserById(userId, realm);
    }
}
 
Example 12
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected UserModel cacheUser(RealmModel realm, UserModel delegate, Long revision) {
    int notBefore = getDelegate().getNotBeforeOfUser(realm, delegate);

    StorageId storageId = delegate.getFederationLink() != null ?
            new StorageId(delegate.getFederationLink(), delegate.getId()) : new StorageId(delegate.getId());
    CachedUser cached = null;
    UserAdapter adapter = null;

    if (!storageId.isLocal()) {
        ComponentModel component = realm.getComponent(storageId.getProviderId());
        UserStorageProviderModel model = new UserStorageProviderModel(component);
        if (!model.isEnabled()) {
            return new ReadOnlyUserModelDelegate(delegate) {
                @Override
                public boolean isEnabled() {
                    return false;
                }
            };
        }
        UserStorageProviderModel.CachePolicy policy = model.getCachePolicy();
        if (policy != null && policy == UserStorageProviderModel.CachePolicy.NO_CACHE) {
            return delegate;
        }

        cached = new CachedUser(revision, realm, delegate, notBefore);
        adapter = new UserAdapter(cached, this, session, realm);
        onCache(realm, adapter, delegate);

        long lifespan = model.getLifespan();
        if (lifespan > 0) {
            cache.addRevisioned(cached, startupRevision, lifespan);
        } else {
            cache.addRevisioned(cached, startupRevision);
        }
    } else {
        cached = new CachedUser(revision, realm, delegate, notBefore);
        adapter = new UserAdapter(cached, this, session, realm);
        onCache(realm, adapter, delegate);
        cache.addRevisioned(cached, startupRevision);
    }

    return adapter;
}
 
Example 13
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) {
    if (socialLink == null) return null;
    if (!realm.isIdentityFederationEnabled()) return null;

    if (realmInvalidations.contains(realm.getId())) {
        return getDelegate().getUserByFederatedIdentity(socialLink, realm);
    }
    String cacheKey = getUserByFederatedIdentityCacheKey(realm.getId(), socialLink);
    if (invalidations.contains(cacheKey)) {
        return getDelegate().getUserByFederatedIdentity(socialLink, realm);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);

    String userId = null;
    if (query == null) {
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getUserByFederatedIdentity(socialLink, realm);
        if (model == null) return null;
        userId = model.getId();
        if (invalidations.contains(userId)) return model;
        if (managedUsers.containsKey(userId)) return managedUsers.get(userId);

        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) {
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }

        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            invalidations.add(cacheKey);
            return getDelegate().getUserByFederatedIdentity(socialLink, realm);

        }
        return getUserById(userId, realm);
    }
}
 
Example 14
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public UserModel findServiceAccount(ClientModel client) {
    String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId();
    logger.tracev("getServiceAccount: {0}", username);
    username = username.toLowerCase();
    RealmModel realm = client.getRealm();
    if (realmInvalidations.contains(realm.getId())) {
        logger.tracev("realmInvalidations");
        return getDelegate().getServiceAccount(client);
    }
    String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
    if (invalidations.contains(cacheKey)) {
        logger.tracev("invalidations");
        return getDelegate().getServiceAccount(client);
    }
    UserListQuery query = cache.get(cacheKey, UserListQuery.class);

    String userId = null;
    if (query == null) {
        logger.tracev("query null");
        Long loaded = cache.getCurrentRevision(cacheKey);
        UserModel model = getDelegate().getServiceAccount(client);
        if (model == null) {
            logger.tracev("model from delegate null");
            return null;
        }
        userId = model.getId();
        if (invalidations.contains(userId)) return model;
        if (managedUsers.containsKey(userId)) {
            logger.tracev("return managed user");
            return managedUsers.get(userId);
        }

        UserModel adapter = getUserAdapter(realm, userId, loaded, model);
        if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
            query = new UserListQuery(loaded, cacheKey, realm, model.getId());
            cache.addRevisioned(query, startupRevision);
        }
        managedUsers.put(userId, adapter);
        return adapter;
    } else {
        userId = query.getUsers().iterator().next();
        if (invalidations.contains(userId)) {
            logger.tracev("invalidated cache return delegate");
            return getDelegate().getUserByUsername(username, realm);

        }
        logger.trace("return getUserById");
        return getUserById(userId, realm);
    }
}
 
Example 15
Source File: IdpEmailVerificationAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void sendVerifyEmail(KeycloakSession session, AuthenticationFlowContext context, UserModel existingUser, BrokeredIdentityContext brokerContext) throws UriBuilderException, IllegalArgumentException {
    RealmModel realm = session.getContext().getRealm();
    UriInfo uriInfo = session.getContext().getUri();
    AuthenticationSessionModel authSession = context.getAuthenticationSession();

    int validityInSecs = realm.getActionTokenGeneratedByUserLifespan(IdpVerifyAccountLinkActionToken.TOKEN_TYPE);
    int absoluteExpirationInSecs = Time.currentTime() + validityInSecs;

    EventBuilder event = context.getEvent().clone().event(EventType.SEND_IDENTITY_PROVIDER_LINK)
            .user(existingUser)
            .detail(Details.USERNAME, existingUser.getUsername())
            .detail(Details.EMAIL, existingUser.getEmail())
            .detail(Details.CODE_ID, authSession.getParentSession().getId())
            .removeDetail(Details.AUTH_METHOD)
            .removeDetail(Details.AUTH_TYPE);

    String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
    IdpVerifyAccountLinkActionToken token = new IdpVerifyAccountLinkActionToken(
      existingUser.getId(), absoluteExpirationInSecs, authSessionEncodedId,
      brokerContext.getUsername(), brokerContext.getIdpConfig().getAlias(), authSession.getClient().getClientId()
    );
    UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo),
            authSession.getClient().getClientId(), authSession.getTabId());
    String link = builder
            .queryParam(Constants.EXECUTION, context.getExecution().getId())
            .build(realm.getName()).toString();
    long expirationInMinutes = TimeUnit.SECONDS.toMinutes(validityInSecs);

    try {
        context.getSession().getProvider(EmailTemplateProvider.class)
                .setRealm(realm)
                .setAuthenticationSession(authSession)
                .setUser(existingUser)
                .setAttribute(EmailTemplateProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext)
                .sendConfirmIdentityBrokerLink(link, expirationInMinutes);

        event.success();
    } catch (EmailException e) {
        event.error(Errors.EMAIL_SEND_FAILED);

        ServicesLogger.LOGGER.confirmBrokerEmailFailed(e);
        Response challenge = context.form()
                .setError(Messages.EMAIL_SENT_ERROR)
                .createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);
        context.failure(AuthenticationFlowError.INTERNAL_ERROR, challenge);
        return;
    }

    showEmailSentPage(context, brokerContext);
}
 
Example 16
Source File: KeycloakIdentity.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakIdentity(AccessToken accessToken, KeycloakSession keycloakSession) {
    if (accessToken == null) {
        throw new ErrorResponseException("invalid_bearer_token", "Could not obtain bearer access_token from request.", Status.FORBIDDEN);
    }
    if (keycloakSession == null) {
        throw new ErrorResponseException("no_keycloak_session", "No keycloak session", Status.FORBIDDEN);
    }
    this.accessToken = accessToken;
    this.keycloakSession = keycloakSession;
    this.realm = keycloakSession.getContext().getRealm();

    Map<String, Collection<String>> attributes = new HashMap<>();

    try {
        ObjectNode objectNode = JsonSerialization.createObjectNode(this.accessToken);
        Iterator<String> iterator = objectNode.fieldNames();

        while (iterator.hasNext()) {
            String fieldName = iterator.next();
            JsonNode fieldValue = objectNode.get(fieldName);
            List<String> values = new ArrayList<>();

            if (fieldValue.isArray()) {
                Iterator<JsonNode> valueIterator = fieldValue.iterator();

                while (valueIterator.hasNext()) {
                    values.add(valueIterator.next().asText());
                }
            } else {
                String value = fieldValue.asText();

                if (StringUtil.isNullOrEmpty(value)) {
                    continue;
                }

                values.add(value);
            }

            if (!values.isEmpty()) {
                attributes.put(fieldName, values);
            }
        }

        AccessToken.Access realmAccess = accessToken.getRealmAccess();

        if (realmAccess != null) {
            attributes.put("kc.realm.roles", realmAccess.getRoles());
        }

        Map<String, AccessToken.Access> resourceAccess = accessToken.getResourceAccess();

        if (resourceAccess != null) {
            resourceAccess.forEach((clientId, access) -> attributes.put("kc.client." + clientId + ".roles", access.getRoles()));
        }

        ClientModel clientModel = getTargetClient();
        UserModel clientUser = null;

        if (clientModel != null) {
            clientUser = this.keycloakSession.users().getServiceAccount(clientModel);
        }

        UserModel userSession = getUserFromSessionState();

        this.resourceServer = clientUser != null && userSession.getId().equals(clientUser.getId());

        if (resourceServer) {
            this.id = clientModel.getId();
        } else {
            this.id = userSession.getId();
        }
    } catch (Exception e) {
        throw new RuntimeException("Error while reading attributes from security token.", e);
    }

    this.attributes = Attributes.from(attributes);
}