【问题标题】:Rails: Return a 401?Rails:返回 401?
【发布时间】:2022-03-28 04:48:02
【问题描述】:

我想返回一个 HTTP 401 错误,作为 declarative_authorizationpermission_denied 方法的一部分。

# triggered when a user accesses a page that they don't have access to
def permission_denied
  # render my default 401 error page?
end

我该怎么做? (如果它很愚蠢,请原谅这个问题......我知道如何在我的公共目录中呈现 401.html 页面,但我认为它不会返回 401 HTTP 标头,这就是我所追求的。)

【问题讨论】:

标签: ruby-on-rails http


【解决方案1】:

您可以添加:status 选项

def permission_denied
  render :file => "public/401.html", :status => :unauthorized
end

【讨论】:

  • 添加:layout => false让页面更干净
  • 在文件名中传递格式显然已被弃用,所以新的方法是render :file => "public/401", :status => :unauthorized
  • 你也可以render nothing: true, status: :unauthorized如果你不想渲染任何文件或文本或模板或...
  • head :unauthorized 无内容
  • 从 Rails 5 开始,不推荐使用 :nothing 进行渲染:DEPRECATION WARNING: `:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.
【解决方案2】:

在这里,您不必通过 cmets 挖掘现代答案。

之前的答案在 Rails 5.1 中已被弃用

将这些中的任何一个放入您的控制器操作中:

渲染文件/模板

render :file => "public/401", :status => :unauthorized

渲染 JSON

render status: :unauthorized, json: { error: "You are not authorized to access this resource. Verify that you are passing passing your token." }

不渲染

head :unauthorized

See ActionController#head

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2018-09-20
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多