每次我点击“使用Github登录”按钮,我都会找不到页面。当我尝试http://127.0.0.1:3000/auth/github/callback
时
我收到一个名为OmniAuth :: Strategies :: OAuth2 :: CallbackError的错误,其中显示“csrf_detected | CSRF detected”。这是我的代码:
initializers / omniauth.rb:
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_ID'], ENV['GITHUB_SECRET'],
:scope => 'user,public_repo',
:redirect_uri => ENV['http://127.0.0.1:3000']
end
routes.rb:
root 'users#new'
get '/auth/:provider/callback' => 'sessions#create'
get '/signout' => 'sessions#destroy', as: :signout
end
views / users / new.html.erb:
<% if current_user %>
<h1> Welcome: </h1>
<h2><%= link_to 'Sign out', signout_path %></h2>
<% else %>
<h2><%= link_to 'Sign in with Github', "/auth/github" %></h2>
<% end %>
sessions_controller.rb:
class SessionsController < ApplicationController
def new
end
def create
auth = request.env["omniauth.auth"]
user = User.where(:provider => auth['provider'], :uid => auth['uid'].to_s).first || User.from_omniauth(auth)
reset_session
session[:user_id] = user.id
redirect_to root_url, :notice => "Signed in!"
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => 'Signed out!'
end
def failure
redirect_to root_url, :alert => "Authentication error: #{params[:message].humanize}"
end
end
user.rb:
class User < ActiveRecord::Base
def self.from_omniauth(auth)
# where(auth.slice(:provider, :uid)).first_or_initialize.tap
create! do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end
application_controller.rb:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
请帮忙!
答案 0 :(得分:0)
我设法通过将scope: 'user:email'
添加到OmniAuth初始值设定项文件中provider
语句的末尾来修复此错误。
Rails.application.config.middleware.use OmniAuth::Builder do
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'], scope: 'user:email'
end
答案 1 :(得分:-1)
错误404表示“找不到文件或目录”。换句话说,服务器接收并理解了您的请求,并且非常愿意满足请求,但您要求的数据不存在。