[英]How to dynamically set the OmniAuth scope on runtime?
我之前曾使用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 鍵動態添加“范圍”
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.