如何在Keycloak中通过脚本映射器将登录URI自定义参数绑定到SAML断言
可以通过Keycloak的Script Mapper实现需求,具体步骤如下
核心思路
由于自定义参数是动态传递的临时值,无法预先存入用户/客户端属性,因此需要先在认证流程中捕获登录URI的查询参数并保存到认证会话,再通过Script Mapper从会话中取出参数,添加到SAML断言属性里。
步骤1:创建自定义认证脚本捕获查询参数
- 登录Keycloak管理控制台,进入目标Realm,点击Authentication -> Flows
- 复制默认的
Browser认证流程,命名为Browser with Custom Param Capture - 在新流程的
Forms节点下,找到Username Password Form,点击Add Executor,选择Script Authenticator - 点击新添加的脚本认证器的Actions -> Config,填写以下内容:
- Name:
Capture Custom Parameter - Script Type:
Groovy - 脚本内容:
def httpRequest = session.getContext().getHttpRequest() def customParam = httpRequest.getUri().getQueryParameters().getFirst("custom_parameter") if (customParam != null) { // 将参数存入认证会话,供后续断言生成使用 session.getContext().getAuthenticationSession().setAuthNote("custom_parameter", customParam) } // 继续执行后续认证步骤 return true
- Name:
- 保存配置后,将Realm的默认浏览器认证流程切换为这个新流程。
步骤2:创建Script Mapper将参数添加到SAML断言
- 进入目标SAML客户端,切换到Mappers标签页
- 点击Create,选择
Script mapper作为Mapper Type,填写配置:- Name:
Custom Parameter to SAML Assertion - Friendly Name:
Custom Parameter(可选,用于SP端识别) - Script Type:
Groovy - 脚本内容:
def authSession = session.getContext().getAuthenticationSession() def customParam = authSession.getAuthNote("custom_parameter") if (customParam != null) { // 创建SAML属性并添加到断言 def attribute = samlBuilder.createAttribute( "custom_parameter", // 可替换为SP要求的属性名称 customParam ) attributeStatement.addAttribute(attribute) }
- Name:
- 保存映射器。
验证
构造包含自定义参数的登录URI:
https://keycloak-server/realms/your-realm/protocol/openid-connect/auth?client_id=your-client-id&redirect_uri=your-redirect-uri&response_type=code&scope=openid&state=your-state-value&custom_parameter=test-123
用户完成登录后,Keycloak向SP发送的SAML断言中会包含custom_parameter属性,值为test-123。
内容的提问来源于stack exchange,提问作者Vivian
相关产品推荐
相关产品推荐

