如何在运行时动态设置 OmniAuth 范围?

How to dynamically set the OmniAuth scope on runtime?

我之前被指过OnmiAuth Dynamic Providers in order to switch provider on runtime, based on the visited domain. My solution is based on omniauth-shopify-oauth2 and :

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :shopify,
  scope: 'read_orders,read_products',
  setup: lambda { |env|
    request         = ActionDispatch::Request.new(env)
    subdomain       = "#{request.subdomain}" != "" ? "#{request.subdomain}." : ""
    domain          = "#{request.domain}"
    full_domain     = subdomain+domain
    shopify_client  = Rails.cache.fetch("#{full_domain}_shopify_client")

    env['omniauth.strategy'].options.merge!(
      {
        client_id:       shopify_client[:client_id],
        client_secret:   shopify_client[:client_secret]
      }
    )
    env['omniauth.strategy'].options[:client_options][:site] = "https://#{request.GET['shop']}"
  }
end

但现在我还需要能够动态设置范围。因此缓存中的 "#{full_domain}_shopify_client" 将包含一个额外的 client_permissions 键,例如'read_orders,read_products''read_products'.

如何重构我的代码才能做到这一点?

这里有一个 link 可能会有帮助:https://github.com/Shopify/omniauth-shopify-oauth2/issues/60

我重新编写了您的脚本,似乎可以实现您的要求。从 :client_permissions 键

动态添加 'scope'
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :shopify,
  setup: lambda { |env|
    request         = ActionDispatch::Request.new(env)
    subdomain       = request.subdomain
    domain          = request.domain
    full_domain     = subdomain+domain
    shopify_client  = Rails.cache.fetch("#{full_domain}_shopify_client")

    env['omniauth.strategy'].options.merge!(
      {
        client_id:       shopify_client[:client_id],
        client_secret:   shopify_client[:client_secret],
        scope:           shopify_client[:client_permissions]
        client_options: {
          site: "https://#{request.GET['shop']}"
        },

      }
    )

end

如果出现 Scope does not match, it may have been tampered with. 错误,您可能还需要在会话中设置 Rails.cache.fetch("#{full_domain}_shopify_client")[:client_permissions] (session['shopify.oauth.scope'])。

strategy = env['omniauth.strategy']
session = strategy.session.with_indifferent_access
env['omniauth.strategy'].options[:scope] = session['shopify.oauth.scope']

在您的设置 lambda 中。

然后,在重定向到 oauth 回调之前(例如从控制器)

subdomain       = request.subdomain
domain          = request.domain
full_domain     = subdomain+domain
shopify_client  = Rails.cache.fetch("#{full_domain}_shopify_client")

session['shopify.oauth.scope'] = shopify_client[:client_permissions]