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

The following examples show how to use org.keycloak.representations.idm.UserRepresentation#getAttributes() . 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: 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 2
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Override
public void setEmailVerifiedUpdatedFlag(String userId, String flag) {
  String fedUserId = getFederatedUserId(userId);
  UserResource resource =
      keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
  UserRepresentation user = resource.toRepresentation();
  Map<String, List<String>> map = user.getAttributes();
  List<String> list = new ArrayList<>();
  list.add(flag);
  if (map == null) {
    map = new HashMap<>();
  }
  map.put(JsonKey.EMAIL_VERIFIED_UPDATED, list);
  user.setAttributes(map);
  resource.update(user);
}
 
Example 3
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Override
public String getEmailVerifiedUpdatedFlag(String userId) {
  String fedUserId = getFederatedUserId(userId);
  UserResource resource =
      keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
  UserRepresentation user = resource.toRepresentation();
  Map<String, List<String>> map = user.getAttributes();
  List<String> list = null;
  if (MapUtils.isNotEmpty(map)) {
    list = map.get(JsonKey.EMAIL_VERIFIED_UPDATED);
  }
  if (CollectionUtils.isNotEmpty(list)) {
    return list.get(0);
  } else {
    return "";
  }
}
 
Example 4
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 5
Source File: TermsAndConditionsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void termsDeclined() {
    loginPage.open();

    loginPage.login("test-user@localhost", "password");

    Assert.assertTrue(termsPage.isCurrent());

    termsPage.declineTerms();

    events.expectLogin().event(EventType.CUSTOM_REQUIRED_ACTION_ERROR).detail(Details.CUSTOM_REQUIRED_ACTION, TermsAndConditions.PROVIDER_ID)
            .error(Errors.REJECTED_BY_USER)
            .removeDetail(Details.CONSENT)
            .session(Matchers.nullValue(String.class))
            .assertEvent();


    // assert user attribute is properly removed
    UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost");
    Map<String,List<String>> attributes = user.getAttributes();
    if (attributes != null) {
        assertNull("expected null for terms acceptance user attribute " + TermsAndConditions.USER_ATTRIBUTE,
                attributes.get(TermsAndConditions.USER_ATTRIBUTE));
    }
}
 
Example 6
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Override
public boolean addUserLoginTime(String userId) {
  boolean response = true;
  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();
    List<String> list = new ArrayList<>();
    if (map == null) {
      map = new HashMap<>();
    }
    List<String> currentLogTime = map.get(JsonKey.CURRENT_LOGIN_TIME);
    if (currentLogTime == null || currentLogTime.isEmpty()) {
      currentLogTime = new ArrayList<>();
      currentLogTime.add(Long.toString(System.currentTimeMillis()));
    } else {
      list.add(currentLogTime.get(0));
      currentLogTime.clear();
      currentLogTime.add(0, Long.toString(System.currentTimeMillis()));
    }
    map.put(JsonKey.CURRENT_LOGIN_TIME, currentLogTime);
    map.put(JsonKey.LAST_LOGIN_TIME, list);
    ur.setAttributes(map);
    resource.update(ur);
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
    response = false;
  }
  return response;
}
 
Example 7
Source File: TermsAndConditionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void termsAccepted() {
    loginPage.open();

    loginPage.login("test-user@localhost", "password");

    Assert.assertTrue(termsPage.isCurrent());

    termsPage.acceptTerms();

    events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION).removeDetail(Details.REDIRECT_URI).detail(Details.CUSTOM_REQUIRED_ACTION, TermsAndConditions.PROVIDER_ID).assertEvent();

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

    events.expectLogin().assertEvent();

    // assert user attribute is properly set
    UserRepresentation user = ActionUtil.findUserWithAdminClient(adminClient, "test-user@localhost");
    Map<String,List<String>> attributes = user.getAttributes();
    assertNotNull("timestamp for terms acceptance was not stored in user attributes", attributes);
    List<String> termsAndConditions = attributes.get(TermsAndConditions.USER_ATTRIBUTE);
    assertTrue("timestamp for terms acceptance was not stored in user attributes as "
            + TermsAndConditions.USER_ATTRIBUTE, termsAndConditions.size() == 1);
    String timestamp = termsAndConditions.get(0);
    assertNotNull("expected non-null timestamp for terms acceptance in user attribute "
            + TermsAndConditions.USER_ATTRIBUTE, timestamp);
    try {
        Integer.parseInt(timestamp);
    }
    catch (NumberFormatException e) {
        fail("timestamp for terms acceptance is not a valid integer: '" + timestamp + "'");
    }
}
 
Example 8
Source File: HardcodedUserAttributeMapperTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected UserRepresentation loginAsUserTwiceWithMapper(
    IdentityProviderMapperSyncMode syncMode, boolean createAfterFirstLogin) {
    final IdentityProviderRepresentation idp = setupIdentityProvider();
    if (!createAfterFirstLogin) {
        createMapperInIdp(idp, syncMode);
    }
    createUserInProviderRealm();

    logInAsUserInIDPForFirstTime();

    UserRepresentation user = findUser(bc.consumerRealmName(), bc.getUserLogin(), bc.getUserEmail());
    if (!createAfterFirstLogin) {
        assertThatAttributeHasBeenAssigned(user);
    } else {
        assertThatAttributeHasNotBeenAssigned(user);
    }

    if (createAfterFirstLogin) {
        createMapperInIdp(idp, syncMode);
    }
    logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

    if (user.getAttributes() != null) {
        user.setAttributes(new HashMap<>());
    }
    adminClient.realm(bc.consumerRealmName()).users().get(user.getId()).update(user);

    logInAsUserInIDP();
    return findUser(bc.consumerRealmName(), bc.getUserLogin(), bc.getUserEmail());
}
 
Example 9
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 4 votes vote down vote up
@Test
@Order(1)
void shouldUpdateRealmWithAddingClientUser() {
    doImport("01_update_realm_add_clientuser.json");

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

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

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

    Map<String, List<String>> updatedUserAttributes = updatedUser.getAttributes();
    assertThat(updatedUserAttributes, notNullValue());
    assertThat(updatedUserAttributes.get("locale"), contains("de"));

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

    // check if login with password is successful
    AccessTokenResponse token = keycloakAuthentication.login(
            REALM_NAME,
            "moped-client",
            "my-special-client-secret",
            "myclientuser",
            "myclientuser123"
    );

    assertThat(token.getToken(), notNullValue());
    assertThat(token.getRefreshToken(), notNullValue());
    assertThat(token.getExpiresIn(), is(greaterThan(0L)));
    assertThat(token.getRefreshExpiresIn(), is(greaterThan(0L)));
    assertThat(token.getTokenType(), is("bearer"));
}
 
Example 10
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 4 votes vote down vote up
@Test
@Order(2)
void shouldUpdateRealmWithChangedClientUserPassword() {
    doImport("02_update_realm_change_clientusers_password.json");

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

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

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

    Map<String, List<String>> updatedUserAttributes = updatedUser.getAttributes();
    assertThat(updatedUserAttributes, notNullValue());
    assertThat(updatedUserAttributes.get("locale"), contains("de"));

    UserRepresentation user = keycloakRepository.getUser(REALM_NAME, "myclientuser");

    assertThat(user.getUsername(), is("myclientuser"));
    assertThat(user.getEmail(), is("[email protected]"));
    assertThat(user.isEnabled(), is(true));
    assertThat(user.getFirstName(), is("My clientuser's firstname"));
    assertThat(user.getLastName(), is("My clientuser's lastname"));

    // check if login with old password fails
    assertThrows(KeycloakAuthentication.AuthenticationException.class, () ->
            keycloakAuthentication.login(
                    REALM_NAME,
                    "moped-client",
                    "my-special-client-secret",
                    "myclientuser",
                    "myclientuser123"
            )
    );

    // check if login with new password is successful
    AccessTokenResponse token = keycloakAuthentication.login(
            REALM_NAME,
            "moped-client",
            "my-special-client-secret",
            "myclientuser",
            "changedclientuser123"
    );

    assertThat(token.getToken(), notNullValue());
    assertThat(token.getRefreshToken(), notNullValue());
    assertThat(token.getExpiresIn(), is(greaterThan(0L)));
    assertThat(token.getRefreshExpiresIn(), is(greaterThan(0L)));
    assertThat(token.getTokenType(), is("bearer"));
}
 
Example 11
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    convertDeprecatedSocialProviders(userRep);

    // Import users just to user storage. Don't federate
    UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
    user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
    user.setCreatedTimestamp(userRep.getCreatedTimestamp());
    user.setEmail(userRep.getEmail());
    if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
    user.setFirstName(userRep.getFirstName());
    user.setLastName(userRep.getLastName());
    user.setFederationLink(userRep.getFederationLink());
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            List<String> value = entry.getValue();
            if (value != null) {
                user.setAttribute(entry.getKey(), new ArrayList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String requiredAction : userRep.getRequiredActions()) {
            try {
                user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
            } catch (IllegalArgumentException iae) {
                user.addRequiredAction(requiredAction);
            }
        }
    }
    createCredentials(userRep, session, newRealm, user, false);
    createFederatedIdentities(userRep, session, newRealm, user);
    createRoleMappings(userRep, user, newRealm);
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            session.users().addConsent(newRealm, user.getId(), consentModel);
        }
    }

    if (userRep.getNotBefore() != null) {
        session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
    }

    if (userRep.getServiceAccountClientId() != null) {
        String clientId = userRep.getServiceAccountClientId();
        ClientModel client = newRealm.getClientByClientId(clientId);
        if (client == null) {
            throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
        }
        user.setServiceAccountClientLink(client.getId());
    }
    createGroups(userRep, newRealm, user);
    return user;
}
 
Example 12
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static void importFederatedUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    UserFederatedStorageProvider federatedStorage = session.userFederatedStorage();
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            if (value != null) {
                federatedStorage.setAttribute(newRealm, userRep.getId(), key, new LinkedList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String action : userRep.getRequiredActions()) {
            federatedStorage.addRequiredAction(newRealm, userRep.getId(), action);
        }
    }
    if (userRep.getCredentials() != null) {
        for (CredentialRepresentation cred : userRep.getCredentials()) {
            federatedStorage.createCredential(newRealm, userRep.getId(), toModel(cred));
        }
    }
    createFederatedRoleMappings(federatedStorage, userRep, newRealm);

    if (userRep.getGroups() != null) {
        for (String path : userRep.getGroups()) {
            GroupModel group = KeycloakModelUtils.findGroupByPath(newRealm, path);
            if (group == null) {
                throw new RuntimeException("Unable to find group specified by path: " + path);

            }
            federatedStorage.joinGroup(newRealm, userRep.getId(), group);
        }
    }

    if (userRep.getFederatedIdentities() != null) {
        for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) {
            FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName());
            federatedStorage.addFederatedIdentity(newRealm, userRep.getId(), mappingModel);
        }
    }
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            federatedStorage.addConsent(newRealm, userRep.getId(), consentModel);
        }
    }
    if (userRep.getNotBefore() != null) {
        federatedStorage.setNotBeforeForUser(newRealm, userRep.getId(), userRep.getNotBefore());
    }


}
 
Example 13
Source File: HardcodedUserAttributeMapperTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void assertThatAttributeHasNotBeenAssigned(UserRepresentation user) {
    if (user.getAttributes() != null) {
        assertThat(user.getAttributes().get(USER_ATTRIBUTE), not(contains(USER_ATTRIBUTE_VALUE)));
    }
}