Search in sources :

Example 21 with CredentialModel

use of org.keycloak.credential.CredentialModel in project keycloak by keycloak.

the class UserResource method setCredentialUserLabel.

/**
 * Update a credential label for a user
 */
@PUT
@Consumes(javax.ws.rs.core.MediaType.TEXT_PLAIN)
@Path("credentials/{credentialId}/userLabel")
public void setCredentialUserLabel(@PathParam("credentialId") final String credentialId, String userLabel) {
    auth.users().requireManage(user);
    CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
    if (credential == null) {
        // we do this to make sure somebody can't phish ids
        if (auth.users().canQuery())
            throw new NotFoundException("Credential not found");
        else
            throw new ForbiddenException();
    }
    session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, userLabel);
}
Also used : ForbiddenException(org.keycloak.services.ForbiddenException) UserCredentialModel(org.keycloak.models.UserCredentialModel) CredentialModel(org.keycloak.credential.CredentialModel) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 22 with CredentialModel

use of org.keycloak.credential.CredentialModel in project keycloak by keycloak.

the class UserStorageTest method testCredentialCRUD.

@Test
@ModelTest
public void testCredentialCRUD(KeycloakSession session) throws Exception {
    AtomicReference<String> passwordId = new AtomicReference<>();
    AtomicReference<String> otp1Id = new AtomicReference<>();
    AtomicReference<String> otp2Id = new AtomicReference<>();
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        Assert.assertFalse(StorageId.isLocalStorage(user));
        Stream<CredentialModel> credentials = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user);
        org.keycloak.testsuite.Assert.assertEquals(0, credentials.count());
        // Create password
        CredentialModel passwordCred = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC");
        passwordCred = currentSession.userCredentialManager().createCredential(realm, user, passwordCred);
        passwordId.set(passwordCred.getId());
        // Create Password and 2 OTP credentials (password was already created)
        CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
        CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2");
        otp1 = currentSession.userCredentialManager().createCredential(realm, user, otp1);
        otp2 = currentSession.userCredentialManager().createCredential(realm, user, otp2);
        otp1Id.set(otp1.getId());
        otp2Id.set(otp2.getId());
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: password, otp1, otp2
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get());
        // Assert can't move password when newPreviousCredential not found
        assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), "not-known"));
        // Assert can't move credential when not found
        assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, "not-known", otp2Id.get()));
        // Move otp2 up
        assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get()));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: password, otp2, otp1
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get());
        // Move otp2 to the top
        org.keycloak.testsuite.Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), null));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: otp2, password, otp1
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get());
        // Move password down
        assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), otp1Id.get()));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: otp2, otp1, password
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get());
        // Remove otp2 down two positions
        assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get()));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: otp2, otp1, password
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get());
        // Remove password
        assertTrue(currentSession.userCredentialManager().removeStoredCredential(realm, user, passwordId.get()));
    });
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
        RealmModel realm = currentSession.realms().getRealmByName("test");
        UserModel user = currentSession.users().getUserByUsername(realm, "thor");
        // Assert priorities: otp2, password
        List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertOrder(list, otp1Id.get(), otp2Id.get());
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) CredentialModel(org.keycloak.credential.CredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) KeycloakSession(org.keycloak.models.KeycloakSession) AtomicReference(java.util.concurrent.atomic.AtomicReference) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 23 with CredentialModel

use of org.keycloak.credential.CredentialModel in project keycloak by keycloak.

the class FederatedStorageExportImportTest method testDir.

@Test
public void testDir() {
    ComponentExportImportTest.clearExportImportProperties(testingClient);
    final String userId = "f:1:path";
    testingClient.server().run(session -> {
        RealmModel realm = new RealmManager(session).createRealm(REALM_NAME);
        RoleModel role = realm.addRole("test-role");
        GroupModel group = realm.createGroup("test-group");
        List<String> attrValues = new LinkedList<>();
        attrValues.add("1");
        attrValues.add("2");
        session.userFederatedStorage().setSingleAttribute(realm, userId, "single1", "value1");
        session.userFederatedStorage().setAttribute(realm, userId, "list1", attrValues);
        session.userFederatedStorage().addRequiredAction(realm, userId, "UPDATE_PASSWORD");
        PasswordCredentialModel credential = FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).encodedCredential("password", realm.getPasswordPolicy().getHashIterations());
        session.userFederatedStorage().createCredential(realm, userId, credential);
        session.userFederatedStorage().grantRole(realm, userId, role);
        session.userFederatedStorage().joinGroup(realm, userId, group);
        session.userFederatedStorage().setNotBeforeForUser(realm, userId, 50);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportDirAbsolutePath = this.exportDirAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(DirExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setDir(exportDirAbsolutePath);
        ExportImportConfig.setRealmName(REALM_NAME);
        ExportImportConfig.setAction(ExportImportConfig.ACTION_EXPORT);
        new ExportImportManager(session).runExport();
        session.realms().removeRealm(realmId);
    });
    testingClient.server().run(session -> {
        Assert.assertNull(session.realms().getRealmByName(REALM_NAME));
        ExportImportConfig.setAction(ExportImportConfig.ACTION_IMPORT);
        new ExportImportManager(session).runImport();
    });
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(REALM_NAME);
        Assert.assertNotNull(realm);
        RoleModel role = realm.getRole("test-role");
        GroupModel group = realm.getGroupById(groupId);
        Assert.assertEquals(1, session.userFederatedStorage().getStoredUsersCount(realm));
        MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, userId);
        Assert.assertEquals(3, attributes.size());
        Assert.assertEquals("value1", attributes.getFirst("single1"));
        Assert.assertTrue(attributes.getList("list1").contains("1"));
        Assert.assertTrue(attributes.getList("list1").contains("2"));
        Assert.assertTrue(session.userFederatedStorage().getRequiredActionsStream(realm, userId).collect(Collectors.toSet()).contains("UPDATE_PASSWORD"));
        Assert.assertTrue(session.userFederatedStorage().getRoleMappingsStream(realm, userId).collect(Collectors.toSet()).contains(role));
        Assert.assertTrue(session.userFederatedStorage().getGroupsStream(realm, userId).collect(Collectors.toSet()).contains(group));
        Assert.assertEquals(50, session.userFederatedStorage().getNotBeforeOfUser(realm, userId));
        List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentialsStream(realm, userId).collect(Collectors.toList());
        Assert.assertEquals(1, creds.size());
        Assert.assertTrue(FederatedStorageExportImportTest.getHashProvider(session, realm.getPasswordPolicy()).verify("password", PasswordCredentialModel.createFromCredentialModel(creds.get(0))));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) GroupModel(org.keycloak.models.GroupModel) ExportImportManager(org.keycloak.exportimport.ExportImportManager) RoleModel(org.keycloak.models.RoleModel) RealmManager(org.keycloak.services.managers.RealmManager) LinkedList(java.util.LinkedList) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 24 with CredentialModel

use of org.keycloak.credential.CredentialModel in project keycloak by keycloak.

the class JpaUserCredentialStore method getStoredCredentialById.

@Override
public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) {
    CredentialEntity entity = em.find(CredentialEntity.class, id);
    if (!checkCredentialEntity(entity, user))
        return null;
    CredentialModel model = toModel(entity);
    return model;
}
Also used : CredentialEntity(org.keycloak.models.jpa.entities.CredentialEntity) CredentialModel(org.keycloak.credential.CredentialModel)

Example 25 with CredentialModel

use of org.keycloak.credential.CredentialModel in project keycloak by keycloak.

the class CredentialModelBackwardsCompatibilityTest method testCredentialModelConfigMap.

@Test
public void testCredentialModelConfigMap() {
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.add("key1", "val11");
    map.add("key1", "val12");
    map.add("key2", "val21");
    CredentialModel credential = new CredentialModel();
    Assert.assertNull(credential.getConfig());
    credential.setConfig(map);
    MultivaluedHashMap<String, String> loadedMap = credential.getConfig();
    Assert.assertEquals(map, loadedMap);
}
Also used : MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) Test(org.junit.Test)

Aggregations

CredentialModel (org.keycloak.credential.CredentialModel)36 Test (org.junit.Test)14 OTPCredentialModel (org.keycloak.models.credential.OTPCredentialModel)14 PasswordCredentialModel (org.keycloak.models.credential.PasswordCredentialModel)14 UserCredentialModel (org.keycloak.models.UserCredentialModel)10 RealmModel (org.keycloak.models.RealmModel)8 UserModel (org.keycloak.models.UserModel)7 NotFoundException (javax.ws.rs.NotFoundException)6 Path (javax.ws.rs.Path)5 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)5 CredentialRepresentation (org.keycloak.representations.idm.CredentialRepresentation)4 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 CredentialProvider (org.keycloak.credential.CredentialProvider)3 CachedUserModel (org.keycloak.models.cache.CachedUserModel)3 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)3 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)3 LinkedList (java.util.LinkedList)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Consumes (javax.ws.rs.Consumes)2 DELETE (javax.ws.rs.DELETE)2