org.keycloak.representations.idm.CredentialRepresentation Java Examples

The following examples show how to use org.keycloak.representations.idm.CredentialRepresentation. 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: UserTest.java    From keycloak with Apache License 2.0 8 votes vote down vote up
@Test
public void testDeleteCredentials() {
    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "john-doh@localhost");
    List<CredentialRepresentation> creds = user.credentials();
    Assert.assertEquals(1, creds.size());
    CredentialRepresentation credPasswd = creds.get(0);
    Assert.assertEquals("password", credPasswd.getType());

    // Remove password
    user.removeCredential(credPasswd.getId());
    Assert.assertEquals(0, user.credentials().size());

    // Restore password
    credPasswd.setValue("password");
    user.resetPassword(credPasswd);
    Assert.assertEquals(1, user.credentials().size());
}
 
Example #2
Source File: ApiUtil.java    From keycloak with Apache License 2.0 7 votes vote down vote up
public static void resetUserPassword(UserResource userResource, String newPassword, boolean temporary) {
    CredentialRepresentation newCredential = new CredentialRepresentation();
    newCredential.setType(PASSWORD);
    newCredential.setValue(newPassword);
    newCredential.setTemporary(temporary);
    userResource.resetPassword(newCredential);
}
 
Example #3
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 #4
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 #5
Source File: RunHelpers.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static FetchOnServerWrapper<CredentialModel> fetchCredentials(String username) {
    return new FetchOnServerWrapper() {

        @Override
        public FetchOnServer getRunOnServer() {
            return (FetchOnServer) session -> {
                RealmModel realm = session.getContext().getRealm();
                UserModel user = session.users().getUserByUsername(username, realm);
                List<CredentialModel> storedCredentialsByType = session.userCredentialManager().getStoredCredentialsByType(realm, user, CredentialRepresentation.PASSWORD);
                System.out.println(storedCredentialsByType.size());
                return storedCredentialsByType.get(0);
            };
        }

        @Override
        public Class getResultClass() {
            return CredentialModel.class;
        }
    };
}
 
Example #6
Source File: TotpBean.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) {
    this.uriBuilder = uriBuilder;
    this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE);
    if (enabled) {
        List<CredentialModel> otpCredentials = session.userCredentialManager().getStoredCredentialsByType(realm, user, OTPCredentialModel.TYPE);

        if (otpCredentials.isEmpty()) {
            // Credential is configured on userStorage side. Create the "fake" credential similar like we do for the new account console
            CredentialRepresentation credential = createUserStorageCredentialRepresentation(OTPCredentialModel.TYPE);
            this.otpCredentials = Collections.singletonList(RepresentationToModel.toModel(credential));
        } else {
            this.otpCredentials = otpCredentials;
        }
    } else {
        this.otpCredentials = Collections.EMPTY_LIST;
    }

    this.realm = realm;
    this.totpSecret = HmacOTP.generateSecret(20);
    this.totpSecretEncoded = TotpUtils.encode(totpSecret);
    this.totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user);
}
 
Example #7
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createCredentials(UserRepresentation userRep, KeycloakSession session, RealmModel realm, UserModel user, boolean adminRequest) {
    convertDeprecatedCredentialsFormat(userRep);
    if (userRep.getCredentials() != null) {
        for (CredentialRepresentation cred : userRep.getCredentials()) {
            if (cred.getId() != null && session.userCredentialManager().getStoredCredentialById(realm, user, cred.getId()) != null) {
                continue;
            }
            if (cred.getValue() != null && !cred.getValue().isEmpty()) {
                RealmModel origRealm = session.getContext().getRealm();
                try {
                    session.getContext().setRealm(realm);
                    session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false));
                } catch (ModelException ex) {
                    throw new PasswordPolicyNotMetException(ex.getMessage(), user.getUsername(), ex);
                } finally {
                    session.getContext().setRealm(origRealm);
                }
            } else {
                session.userCredentialManager().createCredentialThroughProvider(realm, user, toModel(cred));
            }
        }
    }
}
 
Example #8
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 #9
Source File: BackwardsCompatibilityUserStorageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String addUserAndResetPassword(String username, String password) {
    // Save user and assert he is saved in the new storage
    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setUsername(username);
    Response response = testRealmResource().users().create(user);
    String userId = ApiUtil.getCreatedId(response);

    Assert.assertEquals(backwardsCompProviderId, new StorageId(userId).getProviderId());

    // Update his password
    CredentialRepresentation passwordRep = new CredentialRepresentation();
    passwordRep.setType(CredentialModel.PASSWORD);
    passwordRep.setValue(password);
    passwordRep.setTemporary(false);

    testRealmResource().users().get(userId).resetPassword(passwordRep);

    return userId;
}
 
Example #10
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAndMoveCredentials() {
    importTestRealms();

    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "user-with-two-configured-otp");
    List<CredentialRepresentation> creds = user.credentials();
    List<String> expectedCredIds = Arrays.asList(creds.get(0).getId(), creds.get(1).getId(), creds.get(2).getId());

    // Check actual user credentials
    assertSameIds(expectedCredIds, user.credentials());

    // Move first credential after second one
    user.moveCredentialAfter(expectedCredIds.get(0), expectedCredIds.get(1));
    List<String> newOrderCredIds = Arrays.asList(expectedCredIds.get(1), expectedCredIds.get(0), expectedCredIds.get(2));
    assertSameIds(newOrderCredIds, user.credentials());

    // Move last credential in first position
    user.moveCredentialToFirst(expectedCredIds.get(2));
    newOrderCredIds = Arrays.asList(expectedCredIds.get(2), expectedCredIds.get(1), expectedCredIds.get(0));
    assertSameIds(newOrderCredIds, user.credentials());

    // Restore initial state
    user.moveCredentialToFirst(expectedCredIds.get(1));
    user.moveCredentialToFirst(expectedCredIds.get(0));
    assertSameIds(expectedCredIds, user.credentials());
}
 
Example #11
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 #12
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createUserWithInvalidPolicyPassword() {
    RealmRepresentation rep = realm.toRepresentation();
    String passwordPolicy = rep.getPasswordPolicy();
    rep.setPasswordPolicy("length(8)");
    realm.update(rep);
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user4");
    user.setEmail("user4@localhost");
    CredentialRepresentation rawPassword = new CredentialRepresentation();
    rawPassword.setValue("ABCD");
    rawPassword.setType(CredentialRepresentation.PASSWORD);
    user.setCredentials(Arrays.asList(rawPassword));
    Response response = realm.users().create(user);
    assertEquals(400, response.getStatus());
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("Password policy not met", error.getErrorMessage());
    rep.setPasswordPolicy(passwordPolicy);
    realm.update(rep);
    response.close();
}
 
Example #13
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 #14
Source File: KeycloakTestResource.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 #15
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 #16
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 #17
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 #18
Source File: AccountRestServiceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCredentialsForUserWithoutPassword() throws IOException {
    // This is just to call REST to ensure tokenUtil will authenticate user and create the tokens.
    // We won't be able to authenticate later as user won't have password
    List<AccountCredentialResource.CredentialContainer> credentials = getCredentials();

    // Remove password from the user now
    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "test-user@localhost");
    for (CredentialRepresentation credential : user.credentials()) {
        if (PasswordCredentialModel.TYPE.equals(credential.getType())) {
            user.removeCredential(credential.getId());
        }
    }

    // Get credentials. Ensure user doesn't have password credential and create action is UPDATE_PASSWORD
    credentials = getCredentials();
    AccountCredentialResource.CredentialContainer password = credentials.get(0);
    assertCredentialContainerExpected(password, PasswordCredentialModel.TYPE, CredentialTypeMetadata.Category.BASIC_AUTHENTICATION.toString(),
            "password-display-name", "password-help-text", "kcAuthenticatorPasswordClass",
            UserModel.RequiredAction.UPDATE_PASSWORD.toString(), null, false, 0);

    // Re-add the password to the user
    ApiUtil.resetUserPassword(user, "password", false);

}
 
Example #19
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 #20
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 #21
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 #22
Source File: WebAuthnRegisterAndLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertRegisteredCredentials(String userId, String aaguid, String attestationStatementFormat) {
    List<CredentialRepresentation> credentials = getCredentials(userId);
    credentials.stream().forEach(i -> {
        if (WebAuthnCredentialModel.TYPE_TWOFACTOR.equals(i.getType())) {
            try {
                WebAuthnCredentialData data = JsonSerialization.readValue(i.getCredentialData(), WebAuthnCredentialData.class);
                assertEquals(aaguid, data.getAaguid());
                assertEquals(attestationStatementFormat, data.getAttestationStatementFormat());
            } catch (IOException e) {
                Assert.fail();
            }
        }
    });
}
 
Example #23
Source File: AccountRestServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCRUDCredentialOfDifferentUser() throws IOException {
    // Get credential ID of the OTP credential of the different user thant currently logged user
    UserResource user = ApiUtil.findUserByUsernameId(testRealm(), "user-with-one-configured-otp");
    CredentialRepresentation otpCredential = user.credentials().stream()
            .filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType()))
            .findFirst()
            .get();

    // Test that current user can't update the credential, which belongs to the different user
    SimpleHttp.Response response = SimpleHttp
            .doPut(getAccountUrl("credentials/" + otpCredential.getId() + "/label"), httpClient)
            .auth(tokenUtil.getToken())
            .json("new-label")
            .asResponse();
    assertEquals(404, response.getStatus());

    // Test that current user can't delete the credential, which belongs to the different user
    response = SimpleHttp
            .doDelete(getAccountUrl("credentials/" + otpCredential.getId()), httpClient)
            .acceptJson()
            .auth(tokenUtil.getToken())
            .asResponse();
    assertEquals(404, response.getStatus());

    // Assert credential was not updated or removed
    CredentialRepresentation otpCredentialLoaded = user.credentials().stream()
            .filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType()))
            .findFirst()
            .get();
    Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel()));
}
 
Example #24
Source File: AccountFormServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void removeTotpAsDifferentUser() {
    UserResource user1 = ApiUtil.findUserByUsernameId(testRealm(), "user-with-one-configured-otp");
    CredentialRepresentation otpCredential = user1.credentials().stream()
            .filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType()))
            .findFirst()
            .get();

    // Login as evil user (test-user@localhost) and setup TOTP
    totpPage.open();
    loginPage.login("test-user@localhost", "password");
    Assert.assertTrue(totpPage.isCurrent());

    totpPageSetup();

    totpPage.configure(totp.generateTOTP(totpPage.getTotpSecret()));

    Assert.assertEquals("Mobile authenticator configured.", profilePage.getSuccess());

    String currentStateChecker = driver.findElement(By.id("stateChecker")).getAttribute("value");


    // Try to delete TOTP of "user-with-one-configured-otp" by replace ID of the TOTP credential in the request
    String currentURL = driver.getCurrentUrl();

    String formParameters = "stateChecker=" + currentStateChecker
            + "&submitAction=Delete"
            + "&credentialId=" + otpCredential.getId();

    URLUtils.sendPOSTRequestWithWebDriver(currentURL, formParameters);

    // Assert credential of "user-with-one-configured-otp" was NOT deleted and is still present for the user
    Assert.assertTrue(user1.credentials().stream()
            .anyMatch(credentialRepresentation -> credentialRepresentation.getType().equals(OTPCredentialModel.TYPE)));

    // Remove TOTP for "test-user" and logout
    totpPage.removeTotp();
    totpPage.logout();
}
 
Example #25
Source File: PasswordHistoryPolicyTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void resetUserPassword(UserResource userResource, String newPassword) {
    CredentialRepresentation newCredential = new CredentialRepresentation();
    newCredential.setType(PASSWORD);
    newCredential.setValue(newPassword);
    newCredential.setTemporary(false);
    userResource.resetPassword(newCredential);
}
 
Example #26
Source File: LDAPProvidersIntegrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertPasswordConfiguredThroughLDAPOnly(UserResource user) {
    // Assert password not stored locally
    List<CredentialRepresentation> storedCredentials = user.credentials();
    for (CredentialRepresentation credential : storedCredentials) {
        Assert.assertFalse(PasswordCredentialModel.TYPE.equals(credential.getType()));
    }

    // Assert password is stored in the LDAP
    List<String> userStorageCredentials = user.getConfiguredUserStorageCredentialTypes();
    Assert.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE));
}
 
Example #27
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginShouldFailAfterPasswordDeleted() {
    String userName = "credential-tester";
    String userPass = "s3cr37";
    String userId = createUser(REALM_NAME, userName, userPass);
    getCleanup(REALM_NAME).addUserId(userId);

    String accountUrl = RealmsResource.accountUrl(UriBuilder.fromUri(getAuthServerRoot())).build(REALM_NAME).toString();
    driver.navigate().to(accountUrl);
    assertEquals("Test user should be on the login page.", "Log In", PageUtils.getPageTitle(driver));
    loginPage.login(userName, userPass);
    assertTrue("Test user should be successfully logged in.", driver.getTitle().contains("Account Management"));
    accountPage.logOut();

    Optional<CredentialRepresentation> passwordCredential =
            realm.users().get(userId).credentials().stream()
                    .filter(c -> CredentialRepresentation.PASSWORD.equals(c.getType()))
                    .findFirst();
    assertTrue("Test user should have a password credential set.", passwordCredential.isPresent());
    realm.users().get(userId).removeCredential(passwordCredential.get().getId());

    driver.navigate().to(accountUrl);
    assertEquals("Test user should be on the login page.", "Log In", PageUtils.getPageTitle(driver));
    loginPage.login(userName, userPass);
    assertTrue("Test user should fail to log in after password was deleted.",
            driver.getCurrentUrl().contains(String.format("/realms/%s/login-actions/authenticate", REALM_NAME)));
}
 
Example #28
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 #29
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void updateUserWithRawCredentials() {
    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));

    String id = createUser(user);

    PasswordCredentialModel credential = PasswordCredentialModel
            .createFromCredentialModel(fetchCredentials("user_rawpw"));
    assertNotNull("Expecting credential", credential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, credential.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, credential.getPasswordCredentialData().getHashIterations());
    assertNotEquals("ABCD", credential.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, credential.getType());

    UserResource userResource = realm.users().get(id);
    UserRepresentation userRep = userResource.toRepresentation();

    CredentialRepresentation rawPasswordForUpdate = new CredentialRepresentation();
    rawPasswordForUpdate.setValue("EFGH");
    rawPasswordForUpdate.setType(CredentialRepresentation.PASSWORD);
    userRep.setCredentials(Arrays.asList(rawPasswordForUpdate));

    updateUser(userResource, userRep);

    PasswordCredentialModel updatedCredential = PasswordCredentialModel
            .createFromCredentialModel(fetchCredentials("user_rawpw"));
    assertNotNull("Expecting credential", updatedCredential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, updatedCredential.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, updatedCredential.getPasswordCredentialData().getHashIterations());
    assertNotEquals("EFGH", updatedCredential.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, updatedCredential.getType());
}
 
Example #30
Source File: SigningInTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private SigningInPage.UserCredential getNewestUserCredential(SigningInPage.CredentialType credentialType) {
    List<CredentialRepresentation> credentials = testUserResource().credentials();
    SigningInPage.UserCredential userCredential =
            credentialType.getUserCredential(credentials.get(credentials.size() - 1).getId());
    assertTrue(userCredential.isPresent());
    return userCredential;
}