我正在使用会话控制器通过API调用或rails web应用程序对用户进行身份验证。该代码适用于Web应用程序,但对于api调用,我无法验证CSRF令牌。我已经设定了
protect_from_forgery with: :null_session
在我的应用程序控制器中为null,但仍然出现此错误。有什么想法丢失了吗?
class Drivers::SessionsController < Devise::SessionsController
after_filter :set_csrf_headers, only: [:create, :destroy]
respond_to :json, :html
def create
password = params[:driver][:password]
email = params[:driver][:email]
driver = email.present? && Driver.find_by(email: email)
if driver.valid_password? password
sign_in driver, store: true
driver.reset_authentication_token!
driver.save
respond_to do |format|
format.html {redirect_to drivers_path}
format.json { render json: JSON.pretty_generate(JSON.parse(driver.to_json)), status: 200 }
end
#render json: driver, status: 200
else
render json: { errors: "Invalid email or password" }, status: 422
end
end
protected
def set_csrf_headers
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
end
这是错误:
Started POST "/drivers/login.json?email=driver@test.com&password=[FILTERED]" for ::1 at 2016-08-27 08:11:03 -0400
Processing by Drivers::SessionsController#create as JSON
Parameters: {"email"=>"apidriver@test.com", "password"=>"[FILTERED]"}
Can't verify CSRF token authenticity
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)
我的应用程序控制器文件
class ApplicationController < ActionController::Base
#skip_before_action :verify_authenticity_token
before_filter :set_paper_trail_whodunnit
before_action :configure_permitted_parameters, if: :devise_controller?
respond_to :html, :json
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session
#protect_from_forgery with: :exception
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u|
u.permit(:password, :password_confirmation, :current_password, :first_name, :last_name, :phone_number, :description)
}
devise_parameter_sanitizer.for(:sign_up) { |u|
u.permit(:email, :password, :first_name, :last_name)
}
end
def after_sign_in_path_for(resource)
if current_driver
drivers_path #your path
end
if current_user
new_booking_path
end
end
end