在 Keycloak 的更新用户配置文件中添加自定义验证

Raf*_*fid 7 jboss freemarker single-sign-on wildfly keycloak

login-update-profile.ftl我在named中添加了一个自定义属性organization,它能够将用户的输入保存到Keycloak中。

<div class="${properties.kcFormGroupClass!}">
    <div class="${properties.kcLabelWrapperClass!}">
        <label for="user.attributes.organization" class="${properties.kcLabelClass!}">${msg("organization")}</label>
    </div>
    <div class="${properties.kcInputWrapperClass!}">
        <div class="${properties.kcInputWrapperClass!}">
            <input type="text" id="user.attributes.organization" name="user.attributes.organization" value="${(user.attributes.organization!'')}" class="${properties.kcInputClass!}" aria-invalid="<#if messagesPerField.existsError('organization')>true</#if>"
            />
        </div>

        <#if messagesPerField.existsError('organization')>
            <span id="input-error-organization" class="${properties.kcInputErrorMessageClass!}" aria-live="polite">
                ${kcSanitize(messagesPerField.get('organization'))?no_esc}
            </span>
        </#if>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

如何为该字段添加验证?我需要将其设为必填字段并满足某些条件(例如字符串的长度)。如果输入无效,则会显示错误消息(就像我们在电子邮件或用户名字段中看到的那样)

Raf*_*fid 3

Review Profile我通过在流程中创建服务提供者的自定义实现找到了解决方案First Broker Login。以下是步骤:

    public List<FormMessage> getCustomAttributeError(String organization) {
        List<FormMessage> errors = new ArrayList<>();

        // You can add more conditions & parameters to be validated
        if(Validation.isBlank(organization)){
            errors.add(new FormMessage("organization", "missingOrganizationMessage"));
        }

        return errors;
    }
Run Code Online (Sandbox Code Playgroud)
  • 转到函数并在和actionImpl之间添加以下行:profile.update((attributeName, userModel)catch (ValidationException pve)
    if(getCustomAttributeError(profile.getAttributes().getFirstValue("organization")).size() > 0){
        throw new ValidationException();                
    }
Run Code Online (Sandbox Code Playgroud)
  • catch (ValidationException pve)在后面添加以下行List<FormMessage> errors
    List<FormMessage> extraErrors = getCustomAttributeErrors(profile.getAttributes().getFirstValue("organization"));
    for(FormMessage error : extraErrors) {
        errors.add(error);
    }
Run Code Online (Sandbox Code Playgroud)
  • 打开IdpReviewProfileAuthenticatorFactory.javago togetDisplayType()函数,将返回值改为"Custom Review Profile"
  • 构建,将其部署到 keycloak 中,创建我们命名的流程.jar副本,然后替换为First Broker LoginCustom First Broker LoginCustom First Broker LoginReview ProfileCustom Review Profile
  • 通过单击其操作按钮进行配置Custom Review Profile,给它一个别名,然后Update Profile on First Login变成on
  • 将所需的身份提供商与新的身份提供商绑定Custom First Broker Login