使用Google登录时遇到问题。尝试通过devise
gem在Ruby on Rails和JavaScript中使用它。我在Google控制台中进行了注册,但到目前为止没有任何效果。我遇到OAuth::Unauthorized
错误。
# app/controllers/callbacks_controller.rb
def redirect
client = Signet::OAuth2::Client.new({
client_id: ENV.fetch('Google ID'),
client_secret: ENV.fetch('Google secret'),
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
scope: Google::Apis::GmailV1::AUTH_GMAIL_READONLY,
redirect_uri: url_for(:action => :callback)
})
redirect_to client.authorization_uri.to_s
end
def callback
client = Signet::OAuth2::Client.new({
client_id: ENV.fetch('Google ID'),
client_secret: ENV.fetch('Google secret'),
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
redirect_uri: url_for(:action => :callback),
code: params[:code]
})
response = client.fetch_access_token!
session[:access_token] = response['access_token']
redirect_to url_for(:action => :labels)
end
# app/controllers/sessions_controller.rb
def googleAuth
access_token = request.env["omniauth.auth"]
user = User.from_omniauth(access_token)
log_in(user)
user.google_token = access_token.credentials.token
refresh_token = access_token.credentials.refresh_token
user.google_refresh_token = refresh_token if refresh_token.present?
user.save
redirect_to root_path
end
# config/initializers/ominauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['google id'],
ENV['google secret']
end
# Gemfile
gem 'omniauth-google-oauth2'
gem 'google-api-client', '~> 0.9', require: 'google/apis/gmail_v1'
# config/routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
get "auth/:provider/callback", to: "sessions#googleAuth"
get "auth/failure", to: redirect("/")
# app/model/user.rb
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:omniauthable, :omniauth_providers => [:google]
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
end
end
我希望我的用户能够使用其Gmail帐户进行注册和登录。 尝试了一切之后,可能会使我的代码有些混乱,并确保有一个更好,更干净的解决方案,但我找不到。