如何在运行时动态设置OmniAuth作用域



我之前曾被指向OnmiAuth动态提供程序,以便在运行时根据访问的域切换提供程序。我的解决方案是基于omniauth-shopify-oauth2和这个伟大的答案:

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'

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

这里有一个链接可能会有所帮助: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]

最新更新