org.keycloak.models.UserModel Java Examples

The following examples show how to use org.keycloak.models.UserModel. 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: BackwardsCompatibilityUserStorageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String setupOTPForUserWithRequiredAction(String userId) {
    // Add required action to the user to reset OTP
    UserResource user = testRealmResource().users().get(userId);
    UserRepresentation userRep = user.toRepresentation();
    userRep.setRequiredActions(Arrays.asList(UserModel.RequiredAction.CONFIGURE_TOTP.toString()));
    user.update(userRep);

    // Login as the user and setup OTP
    testRealmAccountPage.navigateTo();
    loginPage.login("otp1", "pass");

    configureTotpRequiredActionPage.assertCurrent();
    String totpSecret = configureTotpRequiredActionPage.getTotpSecret();
    configureTotpRequiredActionPage.configure(totp.generateTOTP(totpSecret));
    assertCurrentUrlStartsWith(testRealmAccountPage);

    // Logout
    testRealmAccountPage.logOut();

    return totpSecret;
}
 
Example #2
Source File: UserMapStorage.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
    if (editMode == UserStorageProvider.EditMode.READ_ONLY) {
        throw new ReadOnlyException("Federated storage is not writable");
    }
    if (!(input instanceof UserCredentialModel)) {
        return false;
    }
    if (input.getType().equals(PasswordCredentialModel.TYPE)) {
        userPasswords.put(user.getUsername(), input.getChallengeResponse());
        return true;

    } else {
        return false;
    }
}
 
Example #3
Source File: IdpUsernamePasswordForm.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected LoginFormsProvider setupForm(AuthenticationFlowContext context, MultivaluedMap<String, String> formData, Optional<UserModel> existingUser) {
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }

    existingUser.ifPresent(u -> formData.putSingle(AuthenticationManager.FORM_USERNAME, u.getUsername()));

    LoginFormsProvider form = context.form()
            .setFormData(formData)
            .setAttribute(LoginFormsProvider.REGISTRATION_DISABLED, true)
            .setInfo(Messages.FEDERATED_IDENTITY_CONFIRM_REAUTHENTICATE_MESSAGE, serializedCtx.getIdentityProviderId());

    SerializedBrokeredIdentityContext serializedCtx0 = SerializedBrokeredIdentityContext.readFromAuthenticationSession(context.getAuthenticationSession(), AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT);
    if (serializedCtx0 != null) {
        BrokeredIdentityContext ctx0 = serializedCtx0.deserialize(context.getSession(), context.getAuthenticationSession());
        form.setError(Messages.NESTED_FIRST_BROKER_FLOW_MESSAGE, ctx0.getIdpConfig().getAlias(), ctx0.getUsername());
        context.getAuthenticationSession().setAuthNote(AbstractIdpAuthenticator.NESTED_FIRST_BROKER_CONTEXT, null);
    }

    return form;
}
 
Example #4
Source File: LDAPRoleMappingsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test06_newUserDefaultRolesImportModeTest() throws Exception {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();

        // Set a default role on the realm
        appRealm.addDefaultRole("realmRole1");

        UserModel david = session.users().addUser(appRealm, "davidkeycloak");

        RoleModel defaultRole = appRealm.getRole("realmRole1");
        RoleModel realmRole2 = appRealm.getRole("realmRole2");

        Assert.assertNotNull(defaultRole);
        Assert.assertNotNull(realmRole2);

        Set<RoleModel> davidRoles = david.getRealmRoleMappings();

        Assert.assertTrue(davidRoles.contains(defaultRole));
        Assert.assertFalse(davidRoles.contains(realmRole2));

    });
}
 
Example #5
Source File: ProfileBean.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public ProfileBean(UserModel user) {
    this.user = user;

    if (user.getAttributes() != null) {
        for (Map.Entry<String, List<String>> attr : user.getAttributes().entrySet()) {
            List<String> attrValue = attr.getValue();
            if (attrValue != null && attrValue.size() > 0) {
                attributes.put(attr.getKey(), attrValue.get(0));
            }

            if (attrValue != null && attrValue.size() > 1) {
                logger.warnf("There are more values for attribute '%s' of user '%s' . Will display just first value", attr.getKey(), user.getUsername());
            }
        }
    }
}
 
Example #6
Source File: UserSessionProviderOfflineTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void assertSession(UserSessionModel session, UserModel user, String ipAddress, int started,
                                 int lastRefresh, String... clients) {
    assertEquals(user.getId(), session.getUser().getId());
    assertEquals(ipAddress, session.getIpAddress());
    assertEquals(user.getUsername(), session.getLoginUsername());
    assertEquals("form", session.getAuthMethod());
    assertTrue(session.isRememberMe());
    assertTrue((session.getStarted() >= started - 1) && (session.getStarted() <= started + 1));
    assertTrue((session.getLastSessionRefresh() >= lastRefresh - 1) && (session.getLastSessionRefresh() <= lastRefresh + 1));

    String[] actualClients = new String[session.getAuthenticatedClientSessions().size()];
    int i = 0;
    for (Map.Entry<String, AuthenticatedClientSessionModel> entry : session.getAuthenticatedClientSessions().entrySet()) {
        String clientUUID = entry.getKey();
        AuthenticatedClientSessionModel clientSession = entry.getValue();
        Assert.assertEquals(clientUUID, clientSession.getClient().getId());
        actualClients[i] = clientSession.getClient().getClientId();
        i++;
    }
}
 
Example #7
Source File: UserPropertyFileStorage.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults, Predicate<String> matcher) {
    if (maxResults == 0) return Collections.EMPTY_LIST;
    List<UserModel> users = new LinkedList<>();
    int count = 0;
    for (Object un : userPasswords.keySet()) {
        String username = (String)un;
        if (matcher.test(username)) {
            if (count++ < firstResult) {
                continue;
            }
            users.add(createUser(realm, username));
            if (users.size() + 1 > maxResults) break;
        }
    }
    return users;
}
 
Example #8
Source File: PasswordHashingTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private CredentialModel fetchCredentials(String username) {
    return testingClient.server("test").fetch(session -> {
        RealmModel realm = session.getContext().getRealm();
        UserModel user = session.users().getUserByUsername(username, realm);
        return session.userCredentialManager().getStoredCredentialsByType(realm, user, CredentialRepresentation.PASSWORD).get(0);
    }, CredentialModel.class);
}
 
Example #9
Source File: UserCredentialStoreManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected UserCredentialStore getStoreForUser(UserModel user) {
    if (StorageId.isLocalStorage(user)) {
        return (UserCredentialStore) session.userLocalStorage();
    } else {
        return (UserCredentialStore) session.userFederatedStorage();
    }
}
 
Example #10
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getUserByEmail(String email, RealmModel realm) {
    TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class);
    query.setParameter("email", email.toLowerCase());
    query.setParameter("realmId", realm.getId());
    List<UserEntity> results = query.getResultList();

    if (results.isEmpty()) return null;

    ensureEmailConstraint(results, realm);

    return new UserAdapter(session, realm, em, results.get(0));
}
 
Example #11
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected UserModel getUserAdapter(RealmModel realm, String userId, Long loaded, UserModel delegate) {
    CachedUser cached = cache.get(userId, CachedUser.class);
    if (cached == null) {
        return cacheUser(realm, delegate, loaded);
    } else {
        return validateCache(realm, cached);
    }
}
 
Example #12
Source File: DefaultLocaleSelectorProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Locale getUserProfileSelection(RealmModel realm, UserModel user) {
    if (user == null) {
        return null;
    }

    String locale = user.getFirstAttribute(UserModel.LOCALE);
    if (locale == null) {
        return null;
    }

    return findLocale(realm, locale);
}
 
Example #13
Source File: BackwardsCompatibilityUserStorageTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertUserDontHaveDBCredentials() {
    testingClient.server().run(session -> {
        RealmModel realm1 = session.realms().getRealmByName("test");
        UserModel user1 = session.users().getUserByUsername("otp1", realm1);
        List<CredentialModel> keycloakDBCredentials = session.userCredentialManager().getStoredCredentials(realm1, user1);
        Assert.assertTrue(keycloakDBCredentials.isEmpty());
    });
}
 
Example #14
Source File: ResetPassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    if (context.getExecution().isRequired() ||
            (context.getExecution().isConditional() &&
                    configuredFor(context))) {
        context.getAuthenticationSession().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    }
    context.success();
}
 
Example #15
Source File: WebAuthnPasswordlessAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    // ask the user to do required action to register webauthn authenticator
    if (!user.getRequiredActions().contains(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID)) {
        user.addRequiredAction(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID);
    }
}
 
Example #16
Source File: UserCacheSession.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getServiceAccount(ClientModel client) {
    // Just an attempt to find the user from cache by default serviceAccount username
    UserModel user = findServiceAccount(client);
    if (user != null && user.getServiceAccountClientLink() != null && user.getServiceAccountClientLink().equals(client.getId())) {
        return user;
    }

    return getDelegate().getServiceAccount(client);
}
 
Example #17
Source File: HardcodedAttributeMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
 public UserModel proxy(final LDAPObject ldapUser, UserModel delegate, RealmModel realm) {
     String userModelAttrName = getUserModelAttribute();
     String attributeValue = getAttributeValue();

     delegate = new UserModelDelegate(delegate) {

         @Override
         public List<String> getAttribute(String name) {
             if(userModelAttrName.equals(name)){
                 return Arrays.asList(attributeValue);
             }
             return super.getAttribute(name);
         }

         @Override
         public boolean isEmailVerified() {
             if(userModelAttrName.equals("emailVerified")){
                 return Boolean.valueOf(attributeValue);
             }
             return super.isEmailVerified();
         }

         @Override
         public boolean isEnabled() {
             if(userModelAttrName.equals("enabled")){
                 return Boolean.valueOf(attributeValue);
             }
             return super.isEnabled();
         }
        
    };
    return delegate;
}
 
Example #18
Source File: UserMapStorage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getUserById(String id, RealmModel realm) {
    StorageId storageId = new StorageId(id);
    final String username = storageId.getExternalId();
    if (!userPasswords.containsKey(username)) {
        return null;
    }

    return createUser(realm, username);
}
 
Example #19
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: RoleLDAPStorageMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel proxy(LDAPObject ldapUser, UserModel delegate, RealmModel realm) {
    final LDAPGroupMapperMode mode = config.getMode();

    // For IMPORT mode, all operations are performed against local DB
    if (mode == LDAPGroupMapperMode.IMPORT) {
        return delegate;
    } else {
        return new LDAPRoleMappingsUserDelegate(realm, delegate, ldapUser);
    }
}
 
Example #21
Source File: RegistrationValidateMobileFormAction.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {

    // called after successful validation

    UserModel user = context.getUser();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    user.setSingleAttribute(MOBILE_NUMBER_USER_ATTRIBUTE, formData.getFirst(MOBILE_NUMBER_FIELD));
}
 
Example #22
Source File: InternationalizationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void userAttributeTest() {
    testUser.setAttributes(singletonMap(UserModel.LOCALE, singletonList(CUSTOM_LOCALE)));
    testUserResource().update(testUser);

    welcomeScreen.navigateTo();
    welcomeScreen.clickPersonalInfoLink();
    assertEquals(DEFAULT_LOCALE_NAME, loginPage.localeDropdown().getSelected());
    loginToAccount();
    assertCustomLocalePersonalInfo();
}
 
Example #23
Source File: UserConsentModelTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@After
public void after() {
    testingClient.server().run(session -> {

        RealmManager realmManager = new RealmManager(session);
        RealmModel realm = realmManager.getRealmByName("original");

        if (realm != null) {

            session.sessions().removeUserSessions(realm);
            UserModel user = session.users().getUserByUsername("user", realm);
            UserModel user1 = session.users().getUserByUsername("user1", realm);
            UserModel user2 = session.users().getUserByUsername("user2", realm);
            UserModel user3 = session.users().getUserByUsername("user3", realm);

            UserManager um = new UserManager(session);
            if (user != null) {
                um.removeUser(realm, user);
            }
            if (user1 != null) {
                um.removeUser(realm, user1);
            }
            if (user2 != null) {
                um.removeUser(realm, user2);
            }
            if (user3 != null) {
                um.removeUser(realm, user3);
            }
            realmManager.removeRealm(realm);
        }
    });
}
 
Example #24
Source File: UsersResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<UserRepresentation> searchForUser(Map<String, String> attributes, RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, Integer firstResult, Integer maxResults, Boolean includeServiceAccounts) {
    session.setAttribute(UserModel.INCLUDE_SERVICE_ACCOUNT, includeServiceAccounts);

    if (!auth.users().canView()) {
        Set<String> groupModels = auth.groups().getGroupsWithViewPermission();

        if (!groupModels.isEmpty()) {
            session.setAttribute(UserModel.GROUPS, groupModels);
        }
    }

    List<UserModel> userModels = session.users().searchForUser(attributes, realm, firstResult, maxResults);

    return toRepresentation(realm, usersEvaluator, briefRepresentation, userModels);
}
 
Example #25
Source File: UserSessionInitializerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertSessionLoaded(List<UserSessionModel> sessions, String id, UserModel user, String ipAddress, int started, int lastRefresh, String... clients) {
    for (UserSessionModel session : sessions) {
        if (session.getId().equals(id)) {
            UserSessionProviderTest.assertSession(session, user, ipAddress, started, lastRefresh, clients);
            return;
        }
    }
    Assert.fail("Session with ID " + id + " not found in the list");
}
 
Example #26
Source File: UserSessionManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserSessionModel createOfflineUserSession(UserModel user, UserSessionModel userSession) {
    if (logger.isTraceEnabled()) {
        logger.tracef("Creating new offline user session. UserSessionID: '%s' , Username: '%s'", userSession.getId(), user.getUsername());
    }

    UserSessionModel offlineUserSession = kcSession.sessions().createOfflineUserSession(userSession);
    persister.createUserSession(offlineUserSession, true);
    return offlineUserSession;
}
 
Example #27
Source File: UserConsentModelTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void deleteUserTest(KeycloakSession session) {
    // Validate user deleted without any referential constraint errors
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionUT) -> {
        KeycloakSession currentSession = sessionUT;
        RealmModel realm = currentSession.realms().getRealm("original");

        UserModel john = currentSession.users().getUserByUsername("john", realm);
        currentSession.users().removeUser(realm, john);
        UserModel mary = currentSession.users().getUserByUsername("mary", realm);
        currentSession.users().removeUser(realm, mary);
    });
}
 
Example #28
Source File: KerberosFederationProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserModel getUserByUsername(String username, RealmModel realm) {
    KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
    if (authenticator.isUserAvailable(username)) {
        // Case when method was called with username including kerberos realm like [email protected] . Authenticator already checked that kerberos realm was correct
        if (username.contains("@")) {
            username = username.split("@")[0];
        }

        return findOrCreateAuthenticatedUser(realm, username);
    } else {
        return null;
    }
}
 
Example #29
Source File: DemoUserStorageProvider.java    From keycloak-user-storage-provider-demo with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserModel> searchForUser(String search, RealmModel realm) {

  log.debugv("search for users: realm={0} search={1}", realm.getId(), search);

  return repository.findUsers(search).stream()
    .map(user -> new UserAdapter(session, realm, model, user))
    .collect(Collectors.toList());
}
 
Example #30
Source File: SimpleAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {

    UserModel user = context.getUser();

    if (user != null) {
        LOG.infof("Pass through: %s%n", user.getUsername());
    } else {
        LOG.infof("Pass through: %s%n", "anonymous");
    }

    context.success();
}