Java Code Examples for org.keycloak.representations.idm.UserRepresentation#setRequiredActions()

The following examples show how to use org.keycloak.representations.idm.UserRepresentation#setRequiredActions() . 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: LoginPageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void languageChangeRequiredActions() {
    ProfileAssume.assumeCommunity();

    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "test-user@localhost");
    UserRepresentation userRep = user.toRepresentation();
    userRep.setRequiredActions(Arrays.asList(UserModel.RequiredAction.UPDATE_PASSWORD.toString()));
    user.update(userRep);

    loginPage.open();

    loginPage.login("test-user@localhost", "password");
    changePasswordPage.assertCurrent();
    Assert.assertEquals("English", changePasswordPage.getLanguageDropdownText());

    // Switch language
    switchLanguageToGermanAndBack("Update password", "Passwort aktualisieren", changePasswordPage);

    // Update password
    changePasswordPage.changePassword("password", "password");

    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
}
 
Example 3
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Override
public void setRequiredAction(String userId, String requiredAction) {
  String fedUserId = getFederatedUserId(userId);
  UserResource resource =
      keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);

  UserRepresentation userRepresentation = resource.toRepresentation();
  userRepresentation.setRequiredActions(asList(requiredAction));
  if (KeycloakRequiredActionLinkUtil.VERIFY_EMAIL.equalsIgnoreCase(requiredAction)) {
    userRepresentation.setEmailVerified(false);
  }
  resource.update(userRepresentation);
}
 
Example 4
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addUsersWithTermsAndConditions() {
    List<UserRepresentation> users = new ArrayList<>();
    List<String> requiredActions = new ArrayList<>();
    requiredActions.add("terms_and_conditions");

    for (int i = 0; i < NUM_ENTITIES; i++) {
        UserRepresentation user = createUserRepresentation(USER_PREFIX + i, USER_PREFIX + i + "@foo.com", "foo", "bar", true);
        user.setRequiredActions(requiredActions);
        users.add(user);
    }

    piRep.setUsers(users);
}
 
Example 5
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String createUser(String username, String email) {
    UserRepresentation user = new UserRepresentation();
    user.setUsername(username);
    user.setEmail(email);
    user.setRequiredActions(Collections.emptyList());
    user.setEnabled(true);

    return createUser(user);
}
 
Example 6
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void searchByFirstNameNullForLastName() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setFirstName("Erik");
    user.setRequiredActions(Collections.emptyList());
    user.setEnabled(true);

    createUser(user);

    List<UserRepresentation> users = realm.users().search("Erik", 0, 50);
    assertEquals(1, users.size());
}
 
Example 7
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void searchByLastNameNullForFirstName() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setLastName("de Wit");
    user.setRequiredActions(Collections.emptyList());
    user.setEnabled(true);

    createUser(user);

    List<UserRepresentation> users = realm.users().search("wit", null, null);
    assertEquals(1, users.size());
}
 
Example 8
Source File: UserManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserRepresentation initializeRequiredActions() {
    UserRepresentation user = userResource.toRepresentation();
    if (user != null && user.getRequiredActions() == null) {
        user.setRequiredActions(new ArrayList<String>());
    }
    return user;
}
 
Example 9
Source File: UserManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void addRequiredAction(String... actions) {
    UserRepresentation user = initializeRequiredActions();
    user.setRequiredActions(Arrays.asList(actions));
    userResource.update(user);
}
 
Example 10
Source File: LDAPProvidersIntegrationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void ldapPasswordChangeWithAdminEndpointAndRequiredAction() throws Exception {
    String username = "adminEndpointReqAct";
    String email = username + "@email.cz";

    // Register new LDAP user with password, logout user
    loginPage.open();
    loginPage.clickRegister();
    registerPage.assertCurrent();
    registerPage.register("firstName", "lastName", email,
            username, "Password1", "Password1");


    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    appPage.logout();

    // Test admin endpoint. Assert federated endpoint returns password in LDAP "supportedCredentials", but there is no stored password
    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), username);
    assertPasswordConfiguredThroughLDAPOnly(user);

    // Update password through admin REST endpoint. Assert user can authenticate with the new password
    ApiUtil.resetUserPassword(user, "Password1-updated1", false);

    loginPage.open();

    loginSuccessAndLogout(username, "Password1-updated1");

    // Test admin endpoint. Assert federated endpoint returns password in LDAP "supportedCredentials", but there is no stored password
    assertPasswordConfiguredThroughLDAPOnly(user);

    // Test this just for the import mode. No-import mode doesn't support requiredActions right now
    if (isImportEnabled()) {
        // Update password through required action.
        UserRepresentation user2 = user.toRepresentation();
        user2.setRequiredActions(Arrays.asList(UserModel.RequiredAction.UPDATE_PASSWORD.toString()));
        user.update(user2);

        loginPage.open();
        loginPage.login(username, "Password1-updated1");
        requiredActionChangePasswordPage.assertCurrent();

        requiredActionChangePasswordPage.changePassword("Password1-updated2", "Password1-updated2");

        appPage.assertCurrent();
        appPage.logout();

        // Assert user can authenticate with the new password
        loginSuccessAndLogout(username, "Password1-updated2");

        // Test admin endpoint. Assert federated endpoint returns password in LDAP "supportedCredentials", but there is no stored password
        assertPasswordConfiguredThroughLDAPOnly(user);
    }
}
 
Example 11
Source File: UserStorageOTPTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateOTP() {
    // Add requiredAction to the user for update OTP
    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "test-user");
    UserRepresentation userRep = user.toRepresentation();
    userRep.setRequiredActions(Collections.singletonList(UserModel.RequiredAction.CONFIGURE_TOTP.toString()));
    user.update(userRep);

    // Authenticate as the user
    loginPage.open();
    loginPage.login("test-user", DummyUserFederationProvider.HARDCODED_PASSWORD);
    loginTotpPage.assertCurrent();
    loginTotpPage.login(DummyUserFederationProvider.HARDCODED_OTP);

    // User should be required to update OTP
    loginConfigTotpPage.assertCurrent();

    // Dummy OTP code won't work when configure new OTP
    loginConfigTotpPage.configure(DummyUserFederationProvider.HARDCODED_OTP);
    Assert.assertEquals("Invalid authenticator code.", loginConfigTotpPage.getError());

    // This will save the credential to the local DB
    String totpSecret = loginConfigTotpPage.getTotpSecret();
    log.infof("Totp Secret: %s", totpSecret);
    String totpCode = totp.generateTOTP(totpSecret);
    loginConfigTotpPage.configure(totpCode);

    appPage.assertCurrent();

    // Logout
    appPage.logout();

    // Authenticate as the user again with the dummy OTP should still work
    loginPage.open();
    loginPage.login("test-user", DummyUserFederationProvider.HARDCODED_PASSWORD);
    loginTotpPage.assertCurrent();
    loginTotpPage.login(DummyUserFederationProvider.HARDCODED_OTP);

    appPage.assertCurrent();
    appPage.logout();

    // Authenticate with the new OTP code should work as well
    loginPage.open();
    loginPage.login("test-user", DummyUserFederationProvider.HARDCODED_PASSWORD);
    loginTotpPage.assertCurrent();
    loginTotpPage.login(totp.generateTOTP(totpSecret));

    appPage.assertCurrent();
    appPage.logout();
}
 
Example 12
Source File: ExportUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Full export of user data stored in federated storage (including role mappings and credentials)
 *
 * @param id
 * @return fully exported user representation
 */
public static UserRepresentation exportFederatedUser(KeycloakSession session, RealmModel realm, String id, ExportOptions options) {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setId(id);
    MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, id);
    if (attributes.size() > 0) {
        Map<String, List<String>> attrs = new HashMap<>();
        attrs.putAll(attributes);
        userRep.setAttributes(attrs);
    }

    Set<String> requiredActions = session.userFederatedStorage().getRequiredActions(realm, id);
    if (requiredActions.size() > 0) {
        List<String> actions = new LinkedList<>();
        actions.addAll(requiredActions);
        userRep.setRequiredActions(actions);
    }


    // Social links
    Set<FederatedIdentityModel> socialLinks = session.userFederatedStorage().getFederatedIdentities(id, realm);
    List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<>();
    for (FederatedIdentityModel socialLink : socialLinks) {
        FederatedIdentityRepresentation socialLinkRep = exportSocialLink(socialLink);
        socialLinkReps.add(socialLinkRep);
    }
    if (socialLinkReps.size() > 0) {
        userRep.setFederatedIdentities(socialLinkReps);
    }

    // Role mappings
    if (options.isGroupsAndRolesIncluded()) {
        Set<RoleModel> roles = session.userFederatedStorage().getRoleMappings(realm, id);
        List<String> realmRoleNames = new ArrayList<>();
        Map<String, List<String>> clientRoleNames = new HashMap<>();
        for (RoleModel role : roles) {
            if (role.getContainer() instanceof RealmModel) {
                realmRoleNames.add(role.getName());
            } else {
                ClientModel client = (ClientModel) role.getContainer();
                String clientId = client.getClientId();
                List<String> currentClientRoles = clientRoleNames.get(clientId);
                if (currentClientRoles == null) {
                    currentClientRoles = new ArrayList<>();
                    clientRoleNames.put(clientId, currentClientRoles);
                }

                currentClientRoles.add(role.getName());
            }
        }

        if (realmRoleNames.size() > 0) {
            userRep.setRealmRoles(realmRoleNames);
        }
        if (clientRoleNames.size() > 0) {
            userRep.setClientRoles(clientRoleNames);
        }
    }

    // Credentials
    List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentials(realm, id);
    List<CredentialRepresentation> credReps = new ArrayList<>();
    for (CredentialModel cred : creds) {
        CredentialRepresentation credRep = exportCredential(cred);
        credReps.add(credRep);
    }
    userRep.setCredentials(credReps);

    // Grants
    List<UserConsentModel> consents = session.users().getConsents(realm, id);
    LinkedList<UserConsentRepresentation> consentReps = new LinkedList<>();
    for (UserConsentModel consent : consents) {
        UserConsentRepresentation consentRep = ModelToRepresentation.toRepresentation(consent);
        consentReps.add(consentRep);
    }
    if (consentReps.size() > 0) {
        userRep.setClientConsents(consentReps);
    }

    // Not Before
    int notBefore = session.userFederatedStorage().getNotBeforeOfUser(realm, userRep.getId());
    userRep.setNotBefore(notBefore);

    if (options.isGroupsAndRolesIncluded()) {
        List<String> groups = new LinkedList<>();
        for (GroupModel group : session.userFederatedStorage().getGroups(realm, id)) {
            groups.add(ModelToRepresentation.buildGroupPath(group));
        }
        userRep.setGroups(groups);
    }
    return userRep;
}
 
Example 13
Source File: AbstractKeycloakTest.java    From keycloak with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a user in the given realm and returns its ID.
 *
 * @param realm           Realm name
 * @param username        Username
 * @param password        Password
 * @param requiredActions
 * @return ID of the newly created user
 */
public String createUser(String realm, String username, String password, String... requiredActions) {
    UserRepresentation homer = createUserRepresentation(username, password);
    homer.setRequiredActions(Arrays.asList(requiredActions));

    return ApiUtil.createUserWithAdminClient(adminClient.realm(realm), homer);
}