org.keycloak.representations.idm.UserRepresentation Java Examples

The following examples show how to use org.keycloak.representations.idm.UserRepresentation. 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: UserInvalidationClusterTest.java    From keycloak with Apache License 2.0 8 votes vote down vote up
@Override
protected UserRepresentation testEntityUpdates(UserRepresentation user, boolean backendFailover) {

    // username
    user.setUsername(user.getUsername() + "_updated");
    user = updateEntityOnCurrentFailNode(user, "username");
    verifyEntityUpdateDuringFailover(user, backendFailover);

    // first+lastName
    user.setFirstName(user.getFirstName() + "_updated");
    user.setLastName(user.getLastName() + "_updated");
    user = updateEntityOnCurrentFailNode(user, "firstName/lastName");
    verifyEntityUpdateDuringFailover(user, backendFailover);

    return user;
}
 
Example #2
Source File: LogoutTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Test
public void logoutUserByAdmin() {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    assertTrue(appPage.isCurrent());
    String sessionId = events.expectLogin().assertEvent().getSessionId();

    UserRepresentation user = ApiUtil.findUserByUsername(adminClient.realm("test"), "test-user@localhost");
    Assert.assertEquals((Object) 0, user.getNotBefore());

    adminClient.realm("test").users().get(user.getId()).logout();

    Retry.execute(() -> {
        UserRepresentation u = adminClient.realm("test").users().get(user.getId()).toRepresentation();
        Assert.assertTrue(u.getNotBefore() > 0);

        loginPage.open();
        loginPage.assertCurrent();
    }, 10, 200);
}
 
Example #3
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 7 votes vote down vote up
/**
 * This method will take userid and boolean status to update user status
 *
 * @param userId String
 * @param status boolean
 * @throws ProjectCommonException
 */
private void makeUserActiveOrInactive(String userId, boolean status) {
  try {
    String fedUserId = getFederatedUserId(userId);
    ProjectLogger.log(
        "KeyCloakServiceImpl:makeUserActiveOrInactive: fedration id formed: " + fedUserId,
        LoggerEnum.INFO.name());
    validateUserId(fedUserId);
    Keycloak keycloak = KeyCloakConnectionProvider.getConnection();
    UserResource resource =
        keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
    UserRepresentation ur = resource.toRepresentation();
    ur.setEnabled(status);
    if (isNotNull(resource)) {
      resource.update(ur);
    }
  } catch (Exception e) {
    ProjectLogger.log(
        "KeyCloakServiceImpl:makeUserActiveOrInactive:error occurred while blocking user: " + e,
        LoggerEnum.ERROR.name());
    ProjectUtil.createAndThrowInvalidUserDataException();
  }
}
 
Example #4
Source File: KerberosStandaloneTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * KEYCLOAK-4178
 *
 * Assert it's handled when kerberos realm is unreachable
 *
 * @throws Exception
 */
@Test
@UncaughtServerErrorExpected
public void handleUnknownKerberosRealm() throws Exception {
    // Switch kerberos realm to "unavailable"
    List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
    org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
    ComponentRepresentation kerberosProvider = reps.get(0);
    kerberosProvider.getConfig().putSingle(KerberosConstants.KERBEROS_REALM, "unavailable");
    testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);

    // Try register new user and assert it failed
    UserRepresentation john = new UserRepresentation();
    john.setUsername("john");
    Response response = testRealmResource().users().create(john);
    Assert.assertEquals(500, response.getStatus());
    response.close();
}
 
Example #5
Source File: OwnerReplacementTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    log.debug("Adding test realm for import from testrealm.json");
    RealmRepresentation testRealm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
    testRealms.add(testRealm);

    UserRepresentation user = UserBuilder.create()
            .username("foo@user")
            .email("[email protected]")
            .password("password")
            .build();

    RealmRepresentation realm2 = RealmBuilder.create()
            .name("foo")
            .user(user)
            .build();
    realm2.setId("foo");
    testRealms.add(realm2);
}
 
Example #6
Source File: UserTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Test
public void searchPaginated() {
    createUsers();

    List<UserRepresentation> users = realm.users().search("username", 0, 1);
    assertEquals(1, users.size());
    assertEquals("username1", users.get(0).getUsername());

    users = realm.users().search("username", 5, 2);
    assertEquals(2, users.size());
    assertEquals("username6", users.get(0).getUsername());
    assertEquals("username7", users.get(1).getUsername());

    users = realm.users().search("username", 7, 20);
    assertEquals(2, users.size());
    assertEquals("username8", users.get(0).getUsername());
    assertEquals("username9", users.get(1).getUsername());

    users = realm.users().search("username", 0, 20);
    assertEquals(9, users.size());
}
 
Example #7
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 7 votes vote down vote up
@Override
public String getLastLoginTime(String userId) {
  String lastLoginTime = null;
  try {
    String fedUserId = getFederatedUserId(userId);
    UserResource resource =
        keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
    UserRepresentation ur = resource.toRepresentation();
    Map<String, List<String>> map = ur.getAttributes();
    if (map == null) {
      map = new HashMap<>();
    }
    List<String> list = map.get(JsonKey.LAST_LOGIN_TIME);
    if (list != null && !list.isEmpty()) {
      lastLoginTime = list.get(0);
    }
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
  return lastLoginTime;
}
 
Example #8
Source File: ConsentsTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Before
public void createUser() {
    log.debug("creating user for realm " + providerRealmName());

    UserRepresentation user = new UserRepresentation();
    user.setUsername(getUserLogin());
    user.setEmail(getUserEmail());
    user.setFirstName(getUserFirstName());
    user.setLastName(getUserLastName());
    user.setEmailVerified(true);
    user.setEnabled(true);

    RealmResource realmResource = adminClient.realm(providerRealmName());
    String userId = createUserWithAdminClient(realmResource, user);

    resetUserPassword(realmResource.users().get(userId), getUserPassword(), false);
}
 
Example #9
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateUserWithEmailAsUsername() {
    switchRegistrationEmailAsUsername(true);

    String id = createUser();

    UserResource user = realm.users().get(id);
    UserRepresentation userRep = user.toRepresentation();
    assertEquals("user1@localhost", userRep.getUsername());

    userRep.setEmail("user11@localhost");
    updateUser(user, userRep);

    userRep = realm.users().get(id).toRepresentation();
    assertEquals("user11@localhost", userRep.getUsername());

    switchRegistrationEmailAsUsername(false);
}
 
Example #10
Source File: X509DirectGrantTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void loginForceTemporaryAccountLock() throws Exception {
    X509AuthenticatorConfigModel config = new X509AuthenticatorConfigModel()
            .setMappingSourceType(ISSUERDN)
            .setRegularExpression("OU=(.*?)(?:,|$)")
            .setUserIdentityMapperType(USER_ATTRIBUTE)
            .setCustomAttributeName("x509_certificate_identity");

    AuthenticatorConfigRepresentation cfg = newConfig("x509-directgrant-config", config.getConfig());
    String cfgId = createConfig(directGrantExecution.getId(), cfg);
    Assert.assertNotNull(cfgId);

    UserRepresentation user = testRealm().users().get(userId).toRepresentation();
    Assert.assertNotNull(user);

    user.singleAttribute("x509_certificate_identity", "-");
    this.updateUser(user);

    events.clear();

    oauth.clientId("resource-owner");
    oauth.doGrantAccessTokenRequest("secret", "", "", null);
    oauth.doGrantAccessTokenRequest("secret", "", "", null);
    oauth.doGrantAccessTokenRequest("secret", "", "", null);

    events.clear();
}
 
Example #11
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void salesPostSigChangeContents() {
    UserRepresentation user = createUserRepresentation("bburke-additional-domain", "[email protected]", "Bill", "Burke", true);
    setPasswordFor(user, PASSWORD);

    String resultPage = new SamlClientBuilder()
      .navigateTo(salesPostSigEmailServletPage.buildUri())
      .processSamlResponse(Binding.POST).build()
      .login().user(user).build()
      .processSamlResponse(Binding.POST)
        .transformString(s -> {
            Assert.assertThat(s, containsString(">[email protected]<"));
            s = s.replaceAll("[email protected]", "[email protected]");
            return s;
        })
        .build()
      .executeAndTransform(resp -> EntityUtils.toString(resp.getEntity()));

    Assert.assertThat(resultPage, anyOf(
            containsString("INVALID_SIGNATURE"),
            containsString("Error 403: SRVE0295E: Error reported: 403") //WAS
    ));
}
 
Example #12
Source File: PermissionManagementTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void removeUserWithPermissionTicketTest() throws Exception {
    String userToRemoveID = createUser(REALM_NAME, "user-to-remove", "password");

    ResourceRepresentation resource = addResource("Resource A", "kolo", true);
    AuthzClient authzClient = getAuthzClient();
    PermissionResponse response = authzClient.protection("user-to-remove", "password").permission().create(new PermissionRequest(resource.getId()));
    AuthorizationRequest request = new AuthorizationRequest();
    request.setTicket(response.getTicket());
    request.setClaimToken(authzClient.obtainAccessToken("user-to-remove", "password").getToken());
    try {
        authzClient.authorization().authorize(request);
    } catch (Exception e) {

    }
    assertPersistence(response, resource);

    // Remove the user and expect the user and also hers permission tickets are successfully removed
    adminClient.realm(REALM_NAME).users().delete(userToRemoveID);
    assertThat(adminClient.realm(REALM_NAME).users().list().stream().map(UserRepresentation::getId).collect(Collectors.toList()),
            not(hasItem(userToRemoveID)));
    assertThat(getAuthzClient().protection().permission().findByResource(resource.getId()), is(empty()));
}
 
Example #13
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
@Test
@Order(0)
void shouldCreateRealmWithUser() {
    doImport("00_create_realm_with_user.json");

    RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation();

    assertThat(createdRealm.getRealm(), is(REALM_NAME));
    assertThat(createdRealm.isEnabled(), is(true));

    UserRepresentation createdUser = keycloakRepository.getUser(REALM_NAME, "myuser");
    assertThat(createdUser.getUsername(), is("myuser"));
    assertThat(createdUser.getEmail(), is("[email protected]"));
    assertThat(createdUser.isEnabled(), is(true));
    assertThat(createdUser.getFirstName(), is("My firstname"));
    assertThat(createdUser.getLastName(), is("My lastname"));

    Map<String, List<String>> createdUserAttributes = createdUser.getAttributes();
    assertThat(createdUserAttributes, notNullValue());
    assertThat(createdUserAttributes.get("locale"), contains("de"));
}
 
Example #14
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void createClientWithServiceAccount() {
    ClientRepresentation client = new ClientRepresentation();
    client.setClientId(CLIENT_SERVICE_ACCOUNT);
    client.setName(CLIENT_SERVICE_ACCOUNT);
    client.setRootUrl("http://localhost/foo");
    client.setProtocol("openid-connect");
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setServiceAccountsEnabled(true);
    try (Response resp = testRealmResource().clients().create(client)) {
        String id = ApiUtil.getCreatedId(resp);
        UserRepresentation serviceAccountUser = testRealmResource().clients().get(id).getServiceAccountUser();
        assertNotNull(serviceAccountUser);
    }
}
 
Example #15
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
@Test
@Order(10)
void shouldUpdateRealmUpdateUserChangeGroup() {
    // Create Users
    doImport("10_update_realm_update_user_change_group.json");

    final RealmRepresentation realm = keycloakProvider.get().realm(REALM_NAME).toRepresentation();
    assertThat(realm.getRealm(), is(REALM_NAME));
    assertThat(realm.isEnabled(), is(true));

    final UserRepresentation user = keycloakRepository.getUser(REALM_NAME, "user1");
    assertThat(user.getEmail(), is("[email protected]"));
    assertThat(user.getLastName(), is("lastName1"));
    assertThat(user.getFirstName(), is("firstName1"));

    List<GroupRepresentation> userGroups = getGroupsByUser(user);
    assertThat(userGroups, hasSize(2));

    GroupRepresentation group1 = getGroupsByName(userGroups, "group1");
    assertThat(group1.getName(), is("group1"));

    GroupRepresentation group2 = getGroupsByName(userGroups, "group2");
    assertThat(group2.getName(), is("group2"));
}
 
Example #16
Source File: RealmRolesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * KEYCLOAK-2035 Verifies that Users assigned to Role are being properly retrieved as members in API endpoint for role membership
 */
@Test
public void testUsersInRole() {   
    RoleResource role = resource.get("role-with-users");

    List<UserRepresentation> users = adminClient.realm(REALM_NAME).users().search("test-role-member", null, null, null, null, null);
    assertEquals(1, users.size());
    UserResource user = adminClient.realm(REALM_NAME).users().get(users.get(0).getId());
    UserRepresentation userRep = user.toRepresentation();

    RoleResource roleResource = adminClient.realm(REALM_NAME).roles().get(role.toRepresentation().getName());        
    List<RoleRepresentation> rolesToAdd = new LinkedList<>();
    rolesToAdd.add(roleResource.toRepresentation());
    adminClient.realm(REALM_NAME).users().get(userRep.getId()).roles().realmLevel().add(rolesToAdd);

    roleResource = adminClient.realm(REALM_NAME).roles().get(role.toRepresentation().getName());  
    roleResource.getRoleUserMembers();
    //roleResource.getRoleUserMembers().stream().forEach((member) -> log.infof("Found user {}", member.getUsername()));
    assertEquals(1, roleResource.getRoleUserMembers().size());

}
 
Example #17
Source File: UsersResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private List<UserRepresentation> toRepresentation(RealmModel realm, UserPermissionEvaluator usersEvaluator, Boolean briefRepresentation, List<UserModel> userModels) {
    boolean briefRepresentationB = briefRepresentation != null && briefRepresentation;
    List<UserRepresentation> results = new ArrayList<>();
    boolean canViewGlobal = usersEvaluator.canView();

    usersEvaluator.grantIfNoPermission(session.getAttribute(UserModel.GROUPS) != null);

    for (UserModel user : userModels) {
        if (!canViewGlobal) {
            if (!usersEvaluator.canView(user)) {
                continue;
            }
        }
        UserRepresentation userRep = briefRepresentationB
                ? ModelToRepresentation.toBriefRepresentation(user)
                : ModelToRepresentation.toRepresentation(session, realm, user);
        userRep.setAccess(usersEvaluator.getAccess(user));
        results.add(userRep);
    }
    return results;
}
 
Example #18
Source File: RealmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void clearUserCache() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("clearcacheuser");
    Response response = realm.users().create(user);
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), user, ResourceType.USER);

    realm.users().get(userId).toRepresentation();

    assertTrue(testingClient.testing().cache("users").contains(userId));

    realm.clearUserCache();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "clear-user-cache", ResourceType.REALM);

    assertFalse(testingClient.testing().cache("users").contains(userId));
}
 
Example #19
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void multiTenant2SamlTest() throws Exception {
    multiTenant2SamlPage.setRolesToCheck("user");

    try {
        UserRepresentation user2 = createUserRepresentation("user-tenant2", "[email protected]", "Bill", "Burke", true);
        setPasswordFor(user2, "user-tenant2");
        // check the user in the tenant logs in ok
        assertSuccessfulLogin(multiTenant2SamlPage, user2, tenant2RealmSAMLPostLoginPage, "principal=user-tenant2");
        // check the issuer is the correct tenant
        driver.navigate().to(multiTenant2SamlPage.getUriBuilder().clone().path("getAssertionIssuer").build().toASCIIString());
        waitUntilElement(By.xpath("//body")).text().contains("/auth/realms/tenant2");
        // check logout
        multiTenant2SamlPage.logout();
        checkLoggedOut(multiTenant2SamlPage, tenant2RealmSAMLPostLoginPage);
        // check a user in the other tenant doesn't login
        UserRepresentation user1 = createUserRepresentation("user-tenant1", "[email protected]", "Bill", "Burke", true);
        setPasswordFor(user1, "user-tenant1");
        assertFailedLogin(multiTenant2SamlPage, user1, tenant2RealmSAMLPostLoginPage);
    } finally {
        multiTenant2SamlPage.checkRolesEndPoint(false);
    }
}
 
Example #20
Source File: AuthenticationSessionFailoverClusterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    try {
        adminClient.realm("test").remove();
    } catch (Exception ignore) {
    }

    RealmRepresentation testRealm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
    adminClient.realms().create(testRealm);

    UserRepresentation user = UserBuilder.create()
            .username("login-test")
            .email("[email protected]")
            .enabled(true)
            .requiredAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString())
            .requiredAction(UserModel.RequiredAction.UPDATE_PROFILE.toString())
            .password("password")
            .build();

    userId = ApiUtil.createUserWithAdminClient(adminClient.realm("test"), user);
    getCleanup().addUserId(userId);

    oauth.clientId("test-app");
}
 
Example #21
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupAttributeUserOneGroupMultivalueNoAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    UserRepresentation user = userResource.toRepresentation();
    user.setAttributes(new HashMap<>());
    user.getAttributes().put("group-value", Arrays.asList("user-value1", "user-value2"));
    userResource.update(user);
    // create a group1 with two values
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());
    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value1"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value2"));
    } finally {
        // revert
        user.getAttributes().remove("group-value");
        userResource.update(user);
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example #22
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddUsersWithTermsAndConditions() {
    assertAdminEvents.clear();

    setFail();
    addUsersWithTermsAndConditions();

    PartialImportResults results = doImport();
    assertEquals(NUM_ENTITIES, results.getAdded());

    // Need to do this way as admin events from partial import are unsorted
    Set<String> userIds = new HashSet<>();
    for (int i=0 ; i<NUM_ENTITIES ; i++) {
        AdminEventRepresentation adminEvent = assertAdminEvents.poll();
        Assert.assertEquals(realmId, adminEvent.getRealmId());
        Assert.assertEquals(OperationType.CREATE.name(), adminEvent.getOperationType());
        Assert.assertTrue(adminEvent.getResourcePath().startsWith("users/"));
        String userId = adminEvent.getResourcePath().substring(6);
        userIds.add(userId);
    }

    assertAdminEvents.assertEmpty();

    for (PartialImportResult result : results.getResults()) {
        String id = result.getId();
        UserResource userRsc = testRealmResource().users().get(id);
        UserRepresentation user = userRsc.toRepresentation();
        assertTrue(user.getUsername().startsWith(USER_PREFIX));
        Assert.assertTrue(userIds.contains(id));
    }
}
 
Example #23
Source File: RequiredActionPriorityTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void setupRequiredActions() {
    setRequiredActionEnabled("test", TermsAndConditions.PROVIDER_ID, true, false);

    // Because of changing the password in test case, we need to re-create the user.
    ApiUtil.removeUserByUsername(testRealm(), "test-user@localhost");
    UserRepresentation user = UserBuilder.create().enabled(true).username("test-user@localhost")
            .email("test-user@localhost").build();
    String testUserId = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealm(), user, "password");

    setRequiredActionEnabled("test", testUserId, RequiredAction.UPDATE_PASSWORD.name(), true);
    setRequiredActionEnabled("test", testUserId, RequiredAction.UPDATE_PROFILE.name(), true);
    setRequiredActionEnabled("test", testUserId, TermsAndConditions.PROVIDER_ID, true);
}
 
Example #24
Source File: UserAttributeUpdater.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public UserAttributeUpdater(UserResource resource, RealmResource realmResource) {
    super(resource,
      () -> {
        UserRepresentation r = resource.toRepresentation();
        r.setGroups(resource.groups().stream().map(GroupRepresentation::getPath).collect(Collectors.toList()));
        return r;
      },
      resource::update
    );
    if (this.rep.getAttributes() == null) {
        this.rep.setAttributes(new HashMap<>());
    }
    this.realmResource = realmResource;
}
 
Example #25
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 #26
Source File: LDAPBinaryAttributesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserRepresentation getUserAndAssertPhoto(String username, boolean isPhotoExpected) {
    List<UserRepresentation> johns = adminClient.realm("test").users().search(username, 0, 10);
    Assert.assertEquals(1, johns.size());
    UserRepresentation john = johns.get(0);
    Assert.assertEquals(username, john.getUsername());
    Assert.assertTrue(john.getAttributes().containsKey(LDAPConstants.LDAP_ID)); // Doublecheck it's the LDAP mapped user

    if (isPhotoExpected) {
        Assert.assertEquals(JPEG_PHOTO_BASE64, john.getAttributes().get(LDAPConstants.JPEG_PHOTO).get(0));
    } else {
        Assert.assertFalse(john.getAttributes().containsKey(LDAPConstants.JPEG_PHOTO));
    }
    return john;
}
 
Example #27
Source File: UserSetup.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
public String createUser(String name, String firstName, String lastName) {
    UserRepresentation user = new UserRepresentation();
    user.setUsername(name);
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setEnabled(true);
    user.setCredentials(Arrays.asList(createPassword(PASSWORD)));
    Response response = users.create(user);
    return getCreatedId(response);
}
 
Example #28
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addClients(boolean withServiceAccounts) throws IOException {
    List<ClientRepresentation> clients = new ArrayList<>();
    List<UserRepresentation> serviceAccounts = new ArrayList<>();

    for (int i = 0; i < NUM_ENTITIES; i++) {
        ClientRepresentation client = new ClientRepresentation();
        client.setClientId(CLIENT_PREFIX + i);
        client.setName(CLIENT_PREFIX + i);
        clients.add(client);
        if (withServiceAccounts) {
            client.setServiceAccountsEnabled(true);
            client.setBearerOnly(false);
            client.setPublicClient(false);
            client.setAuthorizationSettings(resourceServerSampleSettings);
            client.setAuthorizationServicesEnabled(true);
            // create the user service account
            UserRepresentation serviceAccount = new UserRepresentation();
            serviceAccount.setUsername(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId());
            serviceAccount.setEnabled(true);
            serviceAccount.setEmail(serviceAccount.getUsername() + "@placeholder.org");
            serviceAccount.setServiceAccountClientId(client.getClientId());
            serviceAccounts.add(serviceAccount);
        }
    }

    if (withServiceAccounts) {
        if (piRep.getUsers() == null) {
            piRep.setUsers(new ArrayList<>());
        }
        piRep.getUsers().addAll(serviceAccounts);
    }
    piRep.setClients(clients);
}
 
Example #29
Source File: AppInitiatedActionUpdateProfileTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
// This tests verifies that AIA still works if you call it after you are
// already logged in.  The other main difference between this and all other
// AIA tests is that the events are posted in a different order.
public void updateProfileLoginFirst() {
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    
    doAIA();

    updateProfilePage.assertCurrent();

    updateProfilePage.update("New first", "New last", "[email protected]", "test-user@localhost");

    events.expectLogin().assertEvent();
    events.expectRequiredAction(EventType.UPDATE_EMAIL).detail(Details.PREVIOUS_EMAIL, "test-user@localhost").detail(Details.UPDATED_EMAIL, "[email protected]").assertEvent();
    events.expectRequiredAction(EventType.UPDATE_PROFILE).assertEvent();

    assertKcActionStatus("success");

    // assert user is really updated in persistent store
    UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost");
    Assert.assertEquals("New first", user.getFirstName());
    Assert.assertEquals("New last", user.getLastName());
    Assert.assertEquals("[email protected]", user.getEmail());
    Assert.assertEquals("test-user@localhost", user.getUsername());
}
 
Example #30
Source File: CustomThemeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    testRealm.setAccountTheme("address");

    UserRepresentation user2 = UserBuilder.create()
            .enabled(true)
            .username("test-user-no-access@localhost")
            .email("test-user-no-access@localhost")
            .password("password")
            .build();

    RealmBuilder.edit(testRealm)
            .user(user2);
}