4

要驗證用戶身份,我在rails中使用了omniauth-google-oauth2 gem。oauth2中的可選作用域omniauth.rb

現在我想提供額外的google api功能,但我不想強制它。但我無法想出一種方法來使特定範圍可選。

我試着在omniauth.rb中添加另一個條目,但它似乎不允許我爲同一提供程序(google_oauth2)添加多個條目。

有沒有辦法在rails應用程序中添加任何可選的作用域?

+0

您是否找到更好的解決方案? – Bazinga

回答

3

您可以使用name選項。這應該與任何OmniAuth供應商合作:

Rails.application.config.middleware.use OmniAuth::Builder do 
    provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { 
    :name => 'google' 
    } 

    provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { 
    :name => 'google_full', 
    :scope => 'original_scope, extra_scope' 
    } 
end 

隨着omniauth - 谷歌 - 的oauth2不過,你可以採取另一種方法:

Rails.application.config.middleware.use OmniAuth::Builder do 
    provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { 
    :name => 'google' 
    } 

    provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', { 
    :name => 'google_full', 
    :scope => 'extra_scope', 
    :prompt => 'consent', 
    :include_granted_scopes => 'true' 
    } 
end 

瞭解更多詳細信息退房Google's Incremental Authorization guide

請注意,通過更改提供商的name,OmniAuth URL將更改爲/auth/new_name,然後request.env['omniauth.auth']['provider']將返回new_name