如果用户未经授权,如何使用 Devise 发送 CORS 标头(401 响应) [英] How to send CORS headers with Devise if user not authorized (401 response)

查看:19
本文介绍了如果用户未经授权,如何使用 Devise 发送 CORS 标头(401 响应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中服务器和使用 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

这个方法在ApplicationController中用作before_filter.

对于某些资源,用户必须经过身份验证和授权.请求是通过 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.

目前我使用的解决方法不是使用设计身份验证方法,而是使用自定义身份验证代码段:

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

这也被设置为 ApplicationController 中的 before_filter.这样设置 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 的默认行为,但必须在 401 响应中设置 CORS 标头.这个怎么做?我必须为此配置 warden 吗?

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 gem https://github.com/cyu/rack-cors 并概述了我在 我的博客.

I successfully used the rack-cors gem https://github.com/cyu/rack-cors and outlined my experience on my blog.

Punchline:指定中间件顺序,使 cors 处理程序在管理员之前:

Punchline: Specify middleware order so cors handler is before warden:

config.middleware.insert_before Warden::Manager, Rack::Cors

这篇关于如果用户未经授权,如何使用 Devise 发送 CORS 标头(401 响应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆