使用 devise 在我的 Rails 应用程序上使用 linkedin 实现 oauth 登录,但是当我单击使用 linkedin 登录时,它会重定向到 linkedin 页面,显示:
糟糕,出了点问题。
这是我到目前为止所做的。 我将这些宝石添加到我的 Gemfile 中
# OAuth LinkedIn
gem 'omniauth-linkedin-oauth2', '~> 1.0'
gem 'omniauth-rails_csrf_protection', '~> 1.0'
并在我的终端上运行
bundle install
创建文件 app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def linkedin
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
sign_in_and_redirect @user, event: :authentication
set_flash_message(:notice, :success, kind: 'LinkedIn') if is_navigational_format?
else
session['devise.linkedin_data'] = request.env['omniauth.auth']
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
added this line into my devise.rb
config.omniauth :linkedin, ENV.fetch('LINKEDIN_KEY'), ENV.fetch('LINKEDIN_SECRET')
在 config/initializers/omniauth.rb 中创建了一个文件
OmniAuth.config.allowed_request_methods = [:get, :post]
Rails.application.config.middleware.use OmniAuth::Builder do
provider :linkedin, ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET']
end
使用命令行创建了迁移文件
rails generate migration AddProviderAndUidToUsers provider:string uid:string
class AddProviderAndUidToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :provider, :string
add_column :users, :uid, :string
add_index :users, [:provider, :uid], unique: true
end
end
在终端运行
rails db:migrate
在我的用户模型上添加了这个:user.rb
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: %i[linkedin]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0, 20]
user.name = auth.info.name
end
end
这是我的路线.rb
devise_for :users, controllers: {
sessions: 'users/sessions', registrations: 'users/registrations',
omniauth_callbacks: 'users/omniauth_callbacks'
}
还将我的客户端 ID 和客户端密钥添加到我的 .env 中 这是我在 linkedin 开发者页面上的回调
啊,我按照浏览器开发者控制台中的请求日志,导致了这个请求:
https://example.ngrok.io/users/auth/linkedin/callback?error=unauthorized_scope_error&error_description=Scope+%26quot%3Br_liteprofile%26quot%3B+is+not+authorized+for+your+application&state=c8986b8aeb7e048b2474ec44f388b57d4da271f10a4b568e
所以,这似乎是一个不允许的范围。我将范围更改为:['openid profile email'],所以:
provider :linkedin, ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET'], :scope => 'openid profile email'
确保 LinkedIn 开发人员门户中的开发人员应用程序显示您可以使用哪些范围:
如果您没有看到任何内容,您可能需要请求访问 OpenID 产品: