如何删除devise authenticate_user中的html重定向 [英] How to remove html redirection in devise authenticate_user

查看:248
本文介绍了如何删除devise authenticate_user中的html重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用devise的authenticate_user!方法在控制器中。当请求中提供的auth_token是正确的,但如果身份验证失败,我最终会出现以下情况:

I use the devise's authenticate_user! method in a controller. This is working fine when the auth_token provided in the request is the correct one but if the authentication fails, I end up with:

curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken'

<html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>

当我使用rabl,最好的方法是使用

As I use rabl, what is the best way to have something like

{'error' : 'authentication error'}

返回的html重定向的整数?

returned intead of the html redirection ?

推荐答案

我这样做避免过滤器:format = :json响应,并且做自己的过滤器来渲染我的JSON响应,如果没有current_user通过

I do that in avoid the filter with :format => :json response and do my own filter to render my JSON response if no current_user pass

class MyController < ApplicationController
  before_filter :authenticate_user!, :unless => { request.format == :json }
  before_filter :user_needed, :if => { request.format == :json }

  def user_needed
    unless current_user
      render :json => {'error' => 'authentication error'}, :status => 401
    end
  end
end

另一种方法可以更清洁的是定义您自己的FailureApp( https://github.com/plataformatec/devise /blob/master/lib/devise/failure_app.rb

An other way, can be cleaner is to define your own FailureApp ( https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb )

class MyFailureApp < Devise::FailureApp
  def respond
    if request.format == :json
      json_failure
    else
      super
    end
  end

  def json_failure
    self.status = 401
    self.content_type = 'application/json'
    self.response_body = "{'error' : 'authentication error'}"
  end
end

在您的Devise配置文件中添加:

In your Devise config file add :

config.warden do |manager| 
  manager.failure_app = MyFailureApp 
end 

这篇关于如何删除devise authenticate_user中的html重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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