Java Code Examples for org.keycloak.representations.idm.CredentialRepresentation#setValue()

The following examples show how to use org.keycloak.representations.idm.CredentialRepresentation#setValue() . 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 11 votes vote down vote up
@Override
public boolean updatePassword(String userId, String password) {
  try {
    String fedUserId = getFederatedUserId(userId);
    UserResource ur = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
    CredentialRepresentation cr = new CredentialRepresentation();
    cr.setType(CredentialRepresentation.PASSWORD);
    cr.setValue(password);
    ur.resetPassword(cr);
    return true;
  } catch (Exception e) {
    ProjectLogger.log(
        "KeyCloakServiceImpl:updatePassword: Exception occurred with error message = " + e,
        LoggerEnum.ERROR.name());
  }
  return false;
}
 
Example 2
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 7 votes vote down vote up
private static UserRepresentation createUser(String username, String... realmRoles) {
    UserRepresentation user = new UserRepresentation();

    user.setUsername(username);
    user.setEnabled(true);
    user.setCredentials(new ArrayList<>());
    user.setRealmRoles(Arrays.asList(realmRoles));

    CredentialRepresentation credential = new CredentialRepresentation();

    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(username);
    credential.setTemporary(false);

    user.getCredentials().add(credential);

    return user;
}
 
Example 3
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static UserRepresentation createUser(String username, String... realmRoles) {
    UserRepresentation user = new UserRepresentation();

    user.setUsername(username);
    user.setEnabled(true);
    user.setCredentials(new ArrayList<>());
    user.setRealmRoles(Arrays.asList(realmRoles));
    user.setEmail(username + "@gmail.com");

    CredentialRepresentation credential = new CredentialRepresentation();

    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(username);
    credential.setTemporary(false);

    user.getCredentials().add(credential);

    return user;
}
 
Example 4
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void resetUserInvalidPassword() {
    String userId = createUser("user1", "user1@localhost");

    try {
        CredentialRepresentation cred = new CredentialRepresentation();
        cred.setType(CredentialRepresentation.PASSWORD);
        cred.setValue(" ");
        cred.setTemporary(false);
        realm.users().get(userId).resetPassword(cred);
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(400, e.getResponse().getStatus());
        e.getResponse().close();
        assertAdminEvents.assertEmpty();
    }
}
 
Example 5
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void createUserWithRawCredentials() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user_rawpw");
    user.setEmail("email.raw@localhost");

    CredentialRepresentation rawPassword = new CredentialRepresentation();
    rawPassword.setValue("ABCD");
    rawPassword.setType(CredentialRepresentation.PASSWORD);
    user.setCredentials(Arrays.asList(rawPassword));

    createUser(user);

    CredentialModel credential = fetchCredentials("user_rawpw");
    assertNotNull("Expecting credential", credential);
    PasswordCredentialModel pcm = PasswordCredentialModel.createFromCredentialModel(credential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, pcm.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, pcm.getPasswordCredentialData().getHashIterations());
    assertNotEquals("ABCD", pcm.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, credential.getType());
}
 
Example 6
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createUserWithTempolaryCredentials() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user_temppw");
    user.setEmail("email.temppw@localhost");

    CredentialRepresentation password = new CredentialRepresentation();
    password.setValue("password");
    password.setType(CredentialRepresentation.PASSWORD);
    password.setTemporary(true);
    user.setCredentials(Arrays.asList(password));

    String userId = createUser(user);

    UserRepresentation userRep = realm.users().get(userId).toRepresentation();
    Assert.assertEquals(1, userRep.getRequiredActions().size());
    Assert.assertEquals(UserModel.RequiredAction.UPDATE_PASSWORD.toString(), userRep.getRequiredActions().get(0));
}
 
Example 7
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * See KEYCLOAK-11003
 */
@Test
public void createUserWithTemporaryPasswordWithAdditionalPasswordUpdateShouldRemoveUpdatePasswordRequiredAction() {

    String userId = createUser();

    CredentialRepresentation credTmp = new CredentialRepresentation();
    credTmp.setType(CredentialRepresentation.PASSWORD);
    credTmp.setValue("temp");
    credTmp.setTemporary(Boolean.TRUE);

    realm.users().get(userId).resetPassword(credTmp);

    CredentialRepresentation credPerm = new CredentialRepresentation();
    credPerm.setType(CredentialRepresentation.PASSWORD);
    credPerm.setValue("perm");
    credPerm.setTemporary(null);

    realm.users().get(userId).resetPassword(credPerm);

    UserRepresentation userRep = realm.users().get(userId).toRepresentation();

    Assert.assertFalse(userRep.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name()));
}
 
Example 8
Source File: HoKTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void configTestRealmForTokenIntrospection(RealmRepresentation testRealm) {
    ClientRepresentation confApp = KeycloakModelUtils.createClient(testRealm, "confidential-cli");
    confApp.setSecret("secret1");
    confApp.setServiceAccountsEnabled(Boolean.TRUE);

    ClientRepresentation pubApp = KeycloakModelUtils.createClient(testRealm, "public-cli");
    pubApp.setPublicClient(Boolean.TRUE);

    UserRepresentation user = new UserRepresentation();
    user.setUsername("no-permissions");
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType("password");
    credential.setValue("password");
    List<CredentialRepresentation> creds = new ArrayList<>();
    creds.add(credential);
    user.setCredentials(creds);
    user.setEnabled(Boolean.TRUE);
    List<String> realmRoles = new ArrayList<>();
    realmRoles.add("user");
    user.setRealmRoles(realmRoles);
    testRealm.getUsers().add(user);
}
 
Example 9
Source File: ServiceAccountTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void failManagePassword() {
    UserResource serviceAccount = adminClient.realm("test").users().get(userId);
    UserRepresentation representation = serviceAccount.toRepresentation();

    CredentialRepresentation password = new CredentialRepresentation();
    password.setValue("password");
    password.setType(CredentialRepresentation.PASSWORD);
    password.setTemporary(false);

    representation.setCredentials(Arrays.asList(password));

    this.expectedException.expect(Matchers.allOf(Matchers.instanceOf(ClientErrorException.class), 
            Matchers.hasProperty("response", Matchers.hasProperty("status", Matchers.is(400)))));
    this.expectedException.reportMissingExceptionWithMessage("Should fail, should not be possible to manage credentials for service accounts");

    serviceAccount.update(representation);
}
 
Example 10
Source File: KeyCloakServiceImpl.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * This method will do the user password update.
 *
 * @param userId String
 * @param password String
 * @return boolean true/false
 */
@Override
public boolean doPasswordUpdate(String userId, String password) {
  boolean response = false;
  try {
    String fedUserId = getFederatedUserId(userId);
    UserResource resource =
        keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId);
    CredentialRepresentation newCredential = new CredentialRepresentation();
    newCredential.setValue(password);
    newCredential.setType(CredentialRepresentation.PASSWORD);
    newCredential.setTemporary(true);
    resource.resetPassword(newCredential);
    response = true;
  } catch (Exception ex) {
    ProjectLogger.log(ex.getMessage(), ex);
  }
  return response;
}
 
Example 11
Source File: KeycloakDevModeRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static UserRepresentation createUser(String username, String... realmRoles) {
    UserRepresentation user = new UserRepresentation();

    user.setUsername(username);
    user.setEnabled(true);
    user.setCredentials(new ArrayList<>());
    user.setRealmRoles(Arrays.asList(realmRoles));

    CredentialRepresentation credential = new CredentialRepresentation();

    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(username);
    credential.setTemporary(false);

    user.getCredentials().add(credential);

    return user;
}
 
Example 12
Source File: DockerTestRealmSetup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void configureUser(final RealmRepresentation dockerRealm, final String username, final String password) {
    final UserRepresentation dockerUser = new UserRepresentation();
    dockerUser.setUsername(username);
    dockerUser.setEnabled(true);
    dockerUser.setEmail("[email protected]");
    dockerUser.setFirstName("docker");
    dockerUser.setLastName("user");

    final CredentialRepresentation dockerUserCreds = new CredentialRepresentation();
    dockerUserCreds.setType(CredentialRepresentation.PASSWORD);
    dockerUserCreds.setValue(password);
    dockerUser.setCredentials(Collections.singletonList(dockerUserCreds));

    dockerRealm.setUsers(Collections.singletonList(dockerUser));
}
 
Example 13
Source File: UserBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * This method adds additional passwords to the user.
 */
public UserBuilder addPassword(String password) {
    if (rep.getCredentials() == null) {
        rep.setCredentials(new LinkedList<>());
    }

    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(password);

    rep.getCredentials().add(credential);
    return this;
}
 
Example 14
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation testRealmRep = loadTestRealm(testRealms);

    testRealmRep.setEventsEnabled(true);

    List<UserRepresentation> users = testRealmRep.getUsers();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("direct-login");
    user.setEmail("direct-login@localhost");
    user.setEnabled(true);
    List<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue("password");
    credentials.add(credential);
    user.setCredentials(credentials);
    users.add(user);

    List<ClientRepresentation> clients = testRealmRep.getClients();

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("resource-owner");
    client.setDirectAccessGrantsEnabled(true);
    client.setSecret("secret");
    clients.add(client);
}
 
Example 15
Source File: FluentTestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a test user.
 *
 * @param username A username to be created.
 * @param password A password for a user.
 * @return <code>this</code>
 */
public FluentTestsHelper createTestUser(String username, String password) {
    UserRepresentation userRepresentation = new UserRepresentation();
    userRepresentation.setUsername(username);
    userRepresentation.setEnabled(true);
    Response response = keycloak.realms().realm(testRealm).users().create(userRepresentation);
    String userId = getCreatedId(response);
    response.close();
    CredentialRepresentation rep = new CredentialRepresentation();
    rep.setType(CredentialRepresentation.PASSWORD);
    rep.setValue(password);
    rep.setTemporary(false);
    keycloak.realms().realm(testRealm).users().get(userId).resetPassword(rep);
    return this;
}
 
Example 16
Source File: TestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean createTestUser(String username, String password, String realmName) throws IOException {

        Keycloak keycloak = Keycloak.getInstance(
                keycloakBaseUrl,
                "master",
                username,
                password,
                "admin-cli");
        UserRepresentation userRepresentation = new UserRepresentation();
        userRepresentation.setUsername(username);
        userRepresentation.setEnabled(Boolean.TRUE);
        Response response = keycloak.realms().realm(realmName).users().create(userRepresentation);
        String userId = getCreatedId(response);
        response.close();
        CredentialRepresentation rep = new CredentialRepresentation();
        rep.setType(CredentialRepresentation.PASSWORD);
        rep.setValue(password);
        rep.setTemporary(false);
        keycloak.realms().realm(realmName).users().get(userId).resetPassword(rep);
        //add roles
        RoleRepresentation representation = new RoleRepresentation();
        representation.setName("user");

        keycloak.realms().realm(realmName).roles().create(representation);
        RoleRepresentation realmRole =  keycloak.realms().realm(realmName).roles().get("user").toRepresentation();
        keycloak.realms().realm(realmName).users().get(userId).roles().realmLevel().add(Arrays.asList(realmRole));
        return true;

    }
 
Example 17
Source File: ManyUsersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public UserRepresentation createUser(UsersResource users, UserRepresentation user) {
    // Add some additional attributes to user
    if (CREATE_OBJECTS) {
        Map<String, List<String>> attrs = new HashMap<>();
        attrs.put("attr1", Collections.singletonList("val1"));
        attrs.put("attr2", Collections.singletonList("val2"));
        user.setAttributes(attrs);
    }

    UserRepresentation userRep = super.createUser(users, user);

    // Add password
    if (CREATE_OBJECTS) {
        CredentialRepresentation password = new CredentialRepresentation();
        password.setType(CredentialRepresentation.PASSWORD);
        password.setValue("password");
        password.setTemporary(false);
        users.get(userRep.getId()).resetPassword(password);
    }

    // Add social link
    if (CREATE_SOCIAL_LINKS) {
        createSocialLink("facebook", users, userRep.getId());
    }

    return userRep;
}
 
Example 18
Source File: UserSetup.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
private CredentialRepresentation createPassword(final String password) {
    CredentialRepresentation passwordCred = new CredentialRepresentation();
    passwordCred.setTemporary(false);
    passwordCred.setType(CredentialRepresentation.PASSWORD);
    passwordCred.setValue(password);
    return passwordCred;
}
 
Example 19
Source File: AbstractClientRegistrationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation rep = new RealmRepresentation();
    rep.setEnabled(true);
    rep.setId(REALM_NAME);
    rep.setRealm(REALM_NAME);
    rep.setUsers(new LinkedList<UserRepresentation>());

    LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation password = new CredentialRepresentation();
    password.setType(CredentialRepresentation.PASSWORD);
    password.setValue("password");
    credentials.add(password);

    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setUsername("manage-clients");
    user.setCredentials(credentials);
    user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));

    rep.getUsers().add(user);

    UserRepresentation user2 = new UserRepresentation();
    user2.setEnabled(true);
    user2.setUsername("create-clients");
    user2.setCredentials(credentials);
    user2.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT)));

    rep.getUsers().add(user2);

    UserRepresentation user3 = new UserRepresentation();
    user3.setEnabled(true);
    user3.setUsername("no-access");
    user3.setCredentials(credentials);

    rep.getUsers().add(user3);

    UserRepresentation appUser = new UserRepresentation();
    appUser.setEnabled(true);
    appUser.setUsername("test-user");
    appUser.setEmail("test-user@localhost");
    appUser.setCredentials(credentials);

    rep.getUsers().add(appUser);

    testRealms.add(rep);
}
 
Example 20
Source File: UserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void resetUserPassword() {
    String userId = createUser("user1", "user1@localhost");

    CredentialRepresentation cred = new CredentialRepresentation();
    cred.setType(CredentialRepresentation.PASSWORD);
    cred.setValue("password");
    cred.setTemporary(false);

    realm.users().get(userId).resetPassword(cred);
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResetPasswordPath(userId), ResourceType.USER);

    String accountUrl = RealmsResource.accountUrl(UriBuilder.fromUri(getAuthServerRoot())).build(REALM_NAME).toString();

    driver.navigate().to(accountUrl);

    assertEquals("Log In", PageUtils.getPageTitle(driver));

    loginPage.login("user1", "password");

    assertTrue(driver.getTitle().contains("Account Management"));
}