如果用户未授权,如何发送CORS头与Devise(401响应) [英] How to send CORS headers with Devise if user not authorized (401 response)
问题描述
我正在开发一个应用程序,其中服务器和使用api的客户端驻留在不同的域,因此我想使用 CORS 。为此,我必须在服务器响应中设置相应的http标头:
I am working on an app, where server and the api-consuming client reside under different domains, so I would like to use CORS. To do so, I have to set corresponding http headers in the server response:
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = 'http://localhost'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*, X-Requested-With, X-Prototype-Version, X-CSRF-Token, Content-Type'
headers['Access-Control-Max-Age'] = "1728000"
end
此方法用作 before_filter
在 ApplicationController
。
对于某些资源,用户必须进行身份验证和授权。请求通过XHR / Ajax完成。因此,如果用户未通过身份验证, Devise 将向客户端发送401响应,而不是重定向到登录页面。但是设置CORS头的过滤器不用于该响应。因此,401响应不被发送到客户端。我想在客户端捕获和使用401响应。
For some resources the user has to be authenticated and authorized. Requests are done via XHR/Ajax. So if the user is not authenticated Devise will send a 401 response to the client, instead of redirecting to a sign in page. But the filter to set the CORS headers is not used for that response. Thus the 401 response is not sent to the client. I want to catch and use the 401 response in the client.
目前我使用一种解决方法,不使用Devise身份验证方法,而是一个自定义验证片段:
Currently I am using a workaround by not using the Devise authentication methods, but a custom auth snippet:
def authenticate_cors_user
if request.xhr? && !user_signed_in?
error = { :error => "You must be logged in." }
render params[:format].to_sym => error, :status => 401
end
end
这被设置为 before_filter
中的 ApplicationController
。这样,设置CORS头的过滤器被触发,一切正常。
This is set as a before_filter
in ApplicationController
, too. This way the filter to set CORS headers gets triggered and everything works fine.
我宁愿使用Devise的默认行为,但是CORS头文件必须设置在401响应。如何做到这一点?我必须为此配置监狱管理员吗?
I would prefer to use the default behaviour of Devise, but the CORS headers would have to be set in the 401 response. How to do this? Do I have to configure warden for that?
如何可以为Devise生成的401响应设置CORS头,而不是创建我自己的响应?
推荐答案
成功地使用了rack-cors宝石 https://github.com/cyu/rack-cors ,并概述了我在< a href =http://mark.nadigs.net/2012/10/16/rails-and-cross-origin-resource-sharing-cors/>我的博客。
I successfully used the rack-cors gem https://github.com/cyu/rack-cors and outlined my experience on my blog.
Punchline:指定中间件顺序,以便cors处理程序在warden之前:
Punchline: Specify middleware order so cors handler is before warden:
config.middleware.insert_before Warden::Manager, Rack::Cors
这篇关于如果用户未授权,如何发送CORS头与Devise(401响应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!