Search in sources :

Example 16 with UserCredentialModel

use of org.keycloak.models.UserCredentialModel in project keycloak by keycloak.

the class OTPCredentialProvider method isValid.

@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) {
    if (!(credentialInput instanceof UserCredentialModel)) {
        logger.debug("Expected instance of UserCredentialModel for CredentialInput");
        return false;
    }
    String challengeResponse = credentialInput.getChallengeResponse();
    if (challengeResponse == null) {
        return false;
    }
    if (ObjectUtil.isBlank(credentialInput.getCredentialId())) {
        logger.debugf("CredentialId is null when validating credential of user %s", user.getUsername());
        return false;
    }
    CredentialModel credential = getCredentialStore().getStoredCredentialById(realm, user, credentialInput.getCredentialId());
    OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromCredentialModel(credential);
    OTPSecretData secretData = otpCredentialModel.getOTPSecretData();
    OTPCredentialData credentialData = otpCredentialModel.getOTPCredentialData();
    OTPPolicy policy = realm.getOTPPolicy();
    if (OTPCredentialModel.HOTP.equals(credentialData.getSubType())) {
        HmacOTP validator = new HmacOTP(credentialData.getDigits(), credentialData.getAlgorithm(), policy.getLookAheadWindow());
        int counter = validator.validateHOTP(challengeResponse, secretData.getValue(), credentialData.getCounter());
        if (counter < 0) {
            return false;
        }
        otpCredentialModel.updateCounter(counter);
        getCredentialStore().updateCredential(realm, user, otpCredentialModel);
        return true;
    } else if (OTPCredentialModel.TOTP.equals(credentialData.getSubType())) {
        TimeBasedOTP validator = new TimeBasedOTP(credentialData.getAlgorithm(), credentialData.getDigits(), credentialData.getPeriod(), policy.getLookAheadWindow());
        return validator.validateTOTP(challengeResponse, secretData.getValue().getBytes(StandardCharsets.UTF_8));
    }
    return false;
}
Also used : OTPSecretData(org.keycloak.models.credential.dto.OTPSecretData) HmacOTP(org.keycloak.models.utils.HmacOTP) UserCredentialModel(org.keycloak.models.UserCredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) TimeBasedOTP(org.keycloak.models.utils.TimeBasedOTP) OTPCredentialData(org.keycloak.models.credential.dto.OTPCredentialData) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) OTPPolicy(org.keycloak.models.OTPPolicy) UserCredentialModel(org.keycloak.models.UserCredentialModel)

Example 17 with UserCredentialModel

use of org.keycloak.models.UserCredentialModel in project keycloak by keycloak.

the class ApplianceBootstrap method createMasterRealmUser.

public void createMasterRealmUser(String username, String password) {
    RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
    session.getContext().setRealm(realm);
    if (session.users().getUsersCount(realm) > 0) {
        throw new IllegalStateException("Can't create initial user as users already exists");
    }
    UserModel adminUser = session.users().addUser(realm, username);
    adminUser.setEnabled(true);
    UserCredentialModel usrCredModel = UserCredentialModel.password(password);
    session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel);
    RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
    adminUser.grantRole(adminRole);
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) RoleModel(org.keycloak.models.RoleModel) UserCredentialModel(org.keycloak.models.UserCredentialModel)

Example 18 with UserCredentialModel

use of org.keycloak.models.UserCredentialModel in project keycloak by keycloak.

the class LDAPTestUtils method addLocalUser.

public static UserModel addLocalUser(KeycloakSession session, RealmModel realm, String username, String email, String password) {
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEmail(email);
    user.setEnabled(true);
    UserCredentialModel creds = UserCredentialModel.password(password);
    session.userCredentialManager().updateCredential(realm, user, creds);
    return user;
}
Also used : UserModel(org.keycloak.models.UserModel) UserCredentialModel(org.keycloak.models.UserCredentialModel)

Example 19 with UserCredentialModel

use of org.keycloak.models.UserCredentialModel in project keycloak by keycloak.

the class LDAPProvidersIntegrationTest method testUnsynced.

@Test
public void testUnsynced() throws Exception {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        UserStorageProviderModel model = new UserStorageProviderModel(ctx.getLdapModel());
        model.getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.UNSYNCED.toString());
        appRealm.updateComponent(model);
    });
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak");
        Assert.assertNotNull(user);
        Assert.assertNotNull(user.getFederationLink());
        Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId());
        UserCredentialModel cred = UserCredentialModel.password("Candycand1", true);
        session.userCredentialManager().updateCredential(appRealm, user, cred);
        CredentialModel userCredentialValueModel = session.userCredentialManager().getStoredCredentialsByTypeStream(appRealm, user, PasswordCredentialModel.TYPE).findFirst().orElse(null);
        Assert.assertNotNull(userCredentialValueModel);
        Assert.assertEquals(PasswordCredentialModel.TYPE, userCredentialValueModel.getType());
        Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred));
        // LDAP password is still unchanged
        try {
            LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johnkeycloak");
            ctx.getLdapProvider().getLdapIdentityStore().validatePassword(ldapUser, "Password1");
        } catch (AuthenticationException ex) {
            throw new RuntimeException(ex);
        }
    });
    // Test admin REST endpoints
    UserResource userResource = ApiUtil.findUserByUsernameId(testRealm(), "johnkeycloak");
    // Assert password is stored locally
    List<String> storedCredentials = userResource.credentials().stream().map(CredentialRepresentation::getType).collect(Collectors.toList());
    Assert.assertTrue(storedCredentials.contains(PasswordCredentialModel.TYPE));
    // Assert password is supported in the LDAP too.
    List<String> userStorageCredentials = userResource.getConfiguredUserStorageCredentialTypes();
    Assert.assertTrue(userStorageCredentials.contains(PasswordCredentialModel.TYPE));
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        UserModel user = session.users().getUserByUsername(appRealm, "johnkeycloak");
        // User is deleted just locally
        Assert.assertTrue(session.users().removeUser(appRealm, user));
        // Assert user not available locally, but will be reimported from LDAP once searched
        Assert.assertNull(session.userLocalStorage().getUserByUsername(appRealm, "johnkeycloak"));
        Assert.assertNotNull(session.users().getUserByUsername(appRealm, "johnkeycloak"));
    });
    // Revert
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
        appRealm.updateComponent(ctx.getLdapModel());
        Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) CachedUserModel(org.keycloak.models.cache.CachedUserModel) UserModel(org.keycloak.models.UserModel) UserCredentialModel(org.keycloak.models.UserCredentialModel) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) AuthenticationException(javax.naming.AuthenticationException) UserResource(org.keycloak.admin.client.resource.UserResource) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) UserCredentialModel(org.keycloak.models.UserCredentialModel) AbstractAuthTest(org.keycloak.testsuite.AbstractAuthTest) Test(org.junit.Test)

Example 20 with UserCredentialModel

use of org.keycloak.models.UserCredentialModel in project keycloak by keycloak.

the class KeycloakModelUtils method generateSecret.

public static CredentialRepresentation generateSecret(ClientRepresentation client) {
    UserCredentialModel secret = UserCredentialModel.generateSecret();
    client.setSecret(secret.getChallengeResponse());
    return ModelToRepresentation.toRepresentation(secret);
}
Also used : UserCredentialModel(org.keycloak.models.UserCredentialModel)

Aggregations

UserCredentialModel (org.keycloak.models.UserCredentialModel)20 UserModel (org.keycloak.models.UserModel)8 CredentialModel (org.keycloak.credential.CredentialModel)5 Response (javax.ws.rs.core.Response)4 OTPCredentialModel (org.keycloak.models.credential.OTPCredentialModel)4 PasswordHashProvider (org.keycloak.credential.hash.PasswordHashProvider)3 CredentialValidationOutput (org.keycloak.models.CredentialValidationOutput)3 PasswordPolicy (org.keycloak.models.PasswordPolicy)3 RealmModel (org.keycloak.models.RealmModel)3 CachedUserModel (org.keycloak.models.cache.CachedUserModel)3 HashMap (java.util.HashMap)2 NotFoundException (javax.ws.rs.NotFoundException)2 Path (javax.ws.rs.Path)2 Test (org.junit.Test)2 SPNEGOAuthenticator (org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator)2 OTPPolicy (org.keycloak.models.OTPPolicy)2 UserCache (org.keycloak.models.cache.UserCache)2 PasswordCredentialModel (org.keycloak.models.credential.PasswordCredentialModel)2 PasswordUserCredentialModel (org.keycloak.models.credential.PasswordUserCredentialModel)2 TimeBasedOTP (org.keycloak.models.utils.TimeBasedOTP)2