使用 Devise,如何自定义失败的身份验证?

Using Devise, how do I customize a failed authentication?

我有一个使用 Devise 来验证操作的控制器。我想要默认行为,即对除一个操作之外的每个操作都使用 401 进行响应。我想继续处理请求,但提供不同的响应正文。

我提供或重写什么方法来完成此操作?

首先,您需要在要执行此操作的页面上跳过标准身份验证..

before_filter :authenticate_user!, except: [:mydifferentcontroller]

然后您将需要为控制器添加一些逻辑以将您带到备用响应

def mydifferentcontroller
  unless user_signed_in?
    ## add redirect_to if you want to send them to an entirely different page or whatever change in logic can go in here 
  end
end

或者如果您只想更改页面的某个部分,您可以使用 user_signed_in?也在视图中

- if user_signed_in?
  .classyclass You're signed in
- else
  .classyclass You're not signed in

如果这就是你的意思....