You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用omniauth-saml实现从SP向IDP传递动态参数及自定义属性

解决方案

方案1:使用官方提供的idp_sso_target_url_runtime_params配置(无需修改源码,推荐)

这个配置项的作用是将你发起SAML登录请求时携带的自定义参数,映射为IDP端可识别的查询参数,自动追加到IDP的SSO跳转地址后,配置步骤如下:

  1. 修改omniauth初始化配置,补充你需要传递的参数映射:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :saml,
    :issuer                             => "my_application",
    :idp_sso_target_url                 => "target_url",
    # 左侧key是你发起请求时带的参数名,右侧value是IDP端要求接收的参数名
    # 如果两端参数名一致可以写相同值
    :idp_sso_target_url_runtime_params  => {
      :first_name => :first_name,
      :last_name => :last_name,
      :email => :email,
      :custom_attr1 => :custom_attr1, # 替换成你的自定义属性
      :custom_attr2 => :custom_attr2
    },
    :idp_cert                           => "-----BEGIN CERTIFICATE-----\n...-----END CERTIFICATE-----",
    :name_identifier_format             => "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
end
  1. 构造页面上的跳转按钮链接,直接在omniauth SAML入口地址后拼接你要传递的动态参数即可:
<!-- 示例ERB按钮,参数可以根据当前登录用户信息动态生成 -->
<%= link_to "跳转至网站1", "/auth/saml?first_name=#{current_user.first_name}&last_name=#{current_user.last_name}&email=#{current_user.email}&custom_attr1=xxx" %>

点击该按钮后,omniauth会自动把你配置的参数映射后追加到IDP的SSO地址后,IDP端可以直接从请求参数中获取对应值。


方案2:自定义SAML策略(适用于需要把参数放入SAML请求体而非URL参数的场景)

如果IDP要求参数必须放在SAML的AuthnRequest请求内容中而非URL查询参数,可以通过继承官方SAML策略重写请求阶段实现,无需使用猴子补丁:

  1. 新建文件app/lib/omniauth/strategies/custom_saml.rb
module OmniAuth
  module Strategies
    class CustomSaml < OmniAuth::Strategies::SAML
      # 重写AuthnRequest构造方法
      def authenticate_request(options = {})
        request = super
        # 把动态参数添加到AuthnRequest的扩展字段中,具体格式根据IDP要求调整
        request_params = Rack::Request.new(@env).params
        request.attributes['first_name'] = request_params['first_name'] if request_params['first_name']
        request.attributes['last_name'] = request_params['last_name'] if request_params['last_name']
        request.attributes['email'] = request_params['email'] if request_params['email']
        request
      end
    end
  end
end
  1. 修改omniauth初始化配置,使用自定义的策略:
Rails.application.config.middleware.use OmniAuth::Builder do
  require 'omniauth/strategies/custom_saml'
  provider :custom_saml,
    # 其余原有配置保持不变
    :issuer => "my_application",
    # ...其余配置和之前一致
end
  1. 跳转链接的构造方式和方案1一致,参数会自动写入SAML请求中。

内容的提问来源于stack exchange,提问作者Aniket Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:06:03