更换
response.headers['X-CSRF-Param'] = request_forgery_protection_token
在我的情况后,在登录,我需要重新绘制用户的菜单中的用户。这很有效,但是在同一部分(当然,没有刷新页面),每次向服务器发送请求时都会收到CSRF真实性错误。以上解决方案无法正常工作,因为我需要呈现js视图。
我所做的这是什么,使用设计:
应用程序/控制器/ sessions_controller.rb
class SessionsController < Devise::SessionsController
respond_to :json
# GET /resource/sign_in
def new
self.resource = resource_class.new(sign_in_params)
clean_up_passwords(resource)
yield resource if block_given?
if request.format.json?
markup = render_to_string :template => "devise/sessions/popup_login", :layout => false
render :json => { :data => markup }.to_json
else
respond_with(resource, serialize_options(resource))
end
end
# POST /resource/sign_in
def create
if request.format.json?
self.resource = warden.authenticate(auth_options)
if resource.nil?
return render json: {status: 'error', message: 'invalid username or password'}
end
sign_in(resource_name, resource)
render json: {status: 'success', message: '¡User authenticated!'}
else
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in)
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
end
end
end
之后,我提出到重绘菜单控制器#行动的请求。而在JavaScript中,我修改了X-CSRF-帕拉姆和X-CSRF令牌:
应用程序/视图/公共事业/ redraw_user_menu.js.erb
$('.js-user-menu').html('');
$('.js-user-menu').append('<%= escape_javascript(render partial: 'shared/user_name_and_icon') %>');
$('meta[name="csrf-param"]').attr('content', '<%= request_forgery_protection_token.to_s %>');
$('meta[name="csrf-token"]').attr('content', '<%= form_authenticity_token %>');
我希望这是有用的人在相同的js情况:)
任何人都知道这个问题是否与Devise开发者一起提出? – IanWhalen 2012-12-29 04:10:33
#2对我不起作用,因为我通过Devise/Ajax通过任何POST请求进行登录后收到CSRF真实性错误。我也不确定如何渲染新的csrf标记,因为我已经将模板渲染为我的':create'动作的最后一步。我在这里提出了一个问题(http://stackoverflow.com/questions/26640326/after-devise-sign-in-via-ajax-any-post-request-results-in-csrf-authenticity-err)并真的很感激,如果你有时刻检查出来 – sixty4bit 2014-10-29 21:36:19
@ sixty4bit我似乎与你有同样的问题,但你的问题已被删除。你有没有发现它? – 2015-07-21 15:01:36