ruby-on-rails - Rails 与 Google Omniauth,由于 CORS 错误而无法与 google 联系
问题描述
所以我正在尝试通过设计使用 Google oauth 配置 Rails,我遵循了此处描述的官方文档。在点击谷歌注册按钮时,我得到了这个错误
Access to fetch at 'url' (redirected from 'http://localhost:3000/users/auth/google_oauth2') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
谷歌搜索我发现你需要启用 CORS,我自然就是这样做的
在我application.rb
的中添加了这个
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :patch, :put]
end
end
这是我的回调控制器
class Users::CallbacksController < Devise::OmniauthCallbacksController
skip_before_action :verify_authenticity_token
def google_oauth2
admin = User.from_omniauth(from_google_params)
redirect_to root_path
end
private
def from_google_params
@from_google_params ||= {
uid: auth.uid,
email: auth.info.email,
full_name: auth.info.name,
avatar_url: auth.info.image,
is_member: false
}
end
def auth
@auth ||= request.env['omniauth.auth']
end
end
编辑 所以经过大量的试验 n 错误后,我让它工作了,有点。所以当我点击谷歌注册时,它仍然会抛出一个错误,
但是,当点击谷歌控制台中的链接时,它成功地去那里,有什么想法吗?
解决方案
devise
使用at master
branch 和 gem尝试此设置omniauth-rails_csrf_protection
设计.rb
config.omniauth :google_oauth2, "API_KEY", "API_SECRET"
路线.rb
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
用户.rb
devise :omniauthable, omniauth_providers: [:google_oauth2]
应用程序/控制器/用户/omniauth_callbacks_controller.rb:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
sign_in_and_redirect @user, event: :authentication
else
session['devise.google_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end
end
end
用户.rb
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
unless user
user = User.create(
email: data['email'],
password: Devise.friendly_token[0,20])
end
user
end
宝石文件:
gem "devise", github: "heartcombo/devise", branch: "master"
gem "omniauth-rails_csrf_protection"
gem "omniauth-google-oauth2"
看法:
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2), method: :post %>
推荐阅读
- selenium-webdriver - 将鼠标悬停在菜单上并单击带有 selenium vba 的子菜单项
- regex - grep 可以删除上下文,但不能删除整行?
- c++ - 使用 C++20 fmt 限制结果的总大小
- c# - 从对象中查找不同并删除重复项
- jquery - 从嵌套的对象数组中获取数据
- c++ - 将 Integer 转换为 4 字节 ungisned char 向量(以 Big endian 字节顺序)
- c++ - ifstream 没有读取任何内容
- c# - WPF子控件继承
- java - 如何更改slf4j logger的日志文件名
- python-3.x - 如何将 ndarray 转换为数组元组?