Search in sources :

Example 16 with CredentialModel

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

the class AccountCredentialResource method setLabel.

/**
 * Update a user label of specified credential of current user
 *
 * @param credentialId ID of the credential, which will be updated
 * @param userLabel new user label as JSON string
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{credentialId}/label")
@NoCache
public void setLabel(@PathParam("credentialId") final String credentialId, String userLabel) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
    if (credential == null) {
        throw new NotFoundException("Credential not found");
    }
    try {
        String label = JsonSerialization.readValue(userLabel, String.class);
        session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, label);
    } catch (IOException ioe) {
        throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST));
    }
}
Also used : CredentialModel(org.keycloak.credential.CredentialModel) NotFoundException(javax.ws.rs.NotFoundException) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache) PUT(javax.ws.rs.PUT)

Example 17 with CredentialModel

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

the class AccountFormServiceTest method assertNumberOfStoredCredentials.

private void assertNumberOfStoredCredentials(int expectedNumberOfStoredCredentials) {
    Assume.assumeTrue("Works only on auth-server-undertow", AuthServerTestEnricher.AUTH_SERVER_CONTAINER.equals(AuthServerTestEnricher.AUTH_SERVER_CONTAINER_DEFAULT));
    // Needed for run-on-server
    final String uId = userId;
    testingClient.server("test").run(session -> {
        RealmModel realm = session.getContext().getRealm();
        UserModel user = session.users().getUserById(realm, uId);
        assertThat(user, Matchers.notNullValue());
        List<CredentialModel> storedCredentials = session.userCredentialManager().getStoredCredentialsStream(realm, user).collect(Collectors.toList());
        assertThat(storedCredentials, Matchers.hasSize(expectedNumberOfStoredCredentials));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) CredentialModel(org.keycloak.credential.CredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 18 with CredentialModel

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

the class UserStorageTest method testCRUDCredentialsOfDifferentUser.

@Test
public void testCRUDCredentialsOfDifferentUser() {
    // Create OTP credential for user1 in the federated storage
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        UserModel user = session.users().getUserByUsername(realm, "thor");
        Assert.assertFalse(StorageId.isLocalStorage(user));
        CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
        session.userCredentialManager().createCredential(realm, user, otp1);
    });
    UserResource user1 = ApiUtil.findUserByUsernameId(testRealmResource(), "thor");
    CredentialRepresentation otpCredential = user1.credentials().stream().filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType())).findFirst().get();
    // Test that when admin operates on user "user2", who is saved in user-storage, he can't update, move or remove credentials of different user "user1"
    UserResource user2 = ApiUtil.findUserByUsernameId(testRealmResource(), "tbrady");
    try {
        user2.setCredentialUserLabel(otpCredential.getId(), "new-label");
        Assert.fail("Not expected to successfully update user label");
    } catch (NotFoundException nfe) {
    // Expected
    }
    try {
        user2.moveCredentialToFirst(otpCredential.getId());
        Assert.fail("Not expected to successfully move credential");
    } catch (NotFoundException nfe) {
    // Expected
    }
    try {
        user2.removeCredential(otpCredential.getId());
        Assert.fail("Not expected to successfully remove credential");
    } catch (NotFoundException nfe) {
    // Expected
    }
    // Assert credential was not removed or updated
    CredentialRepresentation otpCredentialLoaded = user1.credentials().stream().filter(credentialRep -> OTPCredentialModel.TYPE.equals(credentialRep.getType())).findFirst().get();
    Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getUserLabel(), otpCredentialLoaded.getUserLabel()));
    Assert.assertTrue(ObjectUtil.isEqualOrBothNull(otpCredential.getPriority(), otpCredentialLoaded.getPriority()));
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) CredentialModel(org.keycloak.credential.CredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) UserResource(org.keycloak.admin.client.resource.UserResource) NotFoundException(javax.ws.rs.NotFoundException) ModelTest(org.keycloak.testsuite.arquillian.annotation.ModelTest) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 19 with CredentialModel

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

the class FederatedStorageExportImportTest method testSingleFile.

@Test
public void testSingleFile() {
    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);
    });
    final String realmId = testRealmResource().toRepresentation().getId();
    final String groupId = testRealmResource().getGroupByPath("/test-group").getId();
    final String exportFileAbsolutePath = this.exportFileAbsolutePath;
    testingClient.server().run(session -> {
        ExportImportConfig.setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
        ExportImportConfig.setFile(exportFileAbsolutePath);
        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));
        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 20 with CredentialModel

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

the class SecretQuestionCredentialProvider method isValid.

@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
    if (!(input instanceof UserCredentialModel)) {
        logger.debug("Expected instance of UserCredentialModel for CredentialInput");
        return false;
    }
    if (!input.getType().equals(getType())) {
        return false;
    }
    String challengeResponse = input.getChallengeResponse();
    if (challengeResponse == null) {
        return false;
    }
    CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId());
    SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel);
    return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse);
}
Also used : UserCredentialModel(org.keycloak.models.UserCredentialModel) CredentialModel(org.keycloak.credential.CredentialModel) SecretQuestionCredentialModel(org.keycloak.examples.authenticator.credential.SecretQuestionCredentialModel) UserCredentialModel(org.keycloak.models.UserCredentialModel) SecretQuestionCredentialModel(org.keycloak.examples.authenticator.credential.SecretQuestionCredentialModel)

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