keycloakkeycloak-services

Validating Username and Password in Keycloak


I am trying to validate a users username and password from keycloak backend because I have a custom authentication form. I was using the below code to validate the user, which is working as expected.

private UserModel getUserByUserNameAndPassword(AuthenticationFlowContext context, String username,
        String password) {
    RealmModel realm = context.getRealm();
    UserModel user = context.getSession().users().getUserByUsername(realm, username);
    if (user != null) {
        context.setUser(user);
        context.success();
    }
    return user;
}

But I cant validate the password of that user. Can somebody help me to use the password for validating the user.

Thanks in advance.


Solution

  • Here is the solution worked for me. I used validatePassword function in the AbstractUsernameFormAuthenticator class.

    My inputData from form parameter provide username and password.

    private UserModel getUserByUserNameAndPassword(AuthenticationFlowContext context, String username) {
        RealmModel realm = context.getRealm();
        UserModel user = context.getSession().users().getUserByUsername(realm, username);
        MultivaluedMap<String, String> inputData = context.getHttpRequest().getDecodedFormParameters();
        boolean shouldClearUserFromCtxAfterBadPassword = !isUserAlreadySetBeforeUsernamePasswordAuth(context);
    
        if (user != null
                && validatePassword(context, user, inputData, shouldClearUserFromCtxAfterBadPassword)) {
            return user;
        } else {
            return null;
        }
    }