我在Rails API上运行Angular。对于身份验证,我正在拦截401状态:
.config(['$httpProvider', function($httpProvider){
// Prevent rails from making new sessions each time
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
var interceptor = ['$location', '$rootScope', '$q', function($location, $rootScope, $q) {
function success(response) {
return response;
}
function error(response) {
if (response.status === 401) {
$rootScope.$broadcast('event:unauthorized');
$location.path('/login');
return response;
}
return $q.reject(response);
}
return function(promise) {
return promise.then(success, error);
};
}];
$httpProvider.responseInterceptors.push(interceptor);
}])
但拦截器没有触发,因为重定向显示状态为200
Started GET "/api/v1/stages" for 127.0.0.1 at 2014-02-23 04:38:12 +0530
Processing by StagesController#index as HTML
Completed 401 Unauthorized in 5ms
Started GET "/api/v1/users/sign_in" for 127.0.0.1 at 2014-02-23 04:38:12 +0530
Processing by Devise::SessionsController#new as HTML
Rendered /home/kartikluke/.rvm/gems/ruby-2.0.0-p247/gems/devise-3.2.2/app/views/devise/shared/_links.erb (4.3ms)
Rendered /home/kartikluke/.rvm/gems/ruby-2.0.0-p247/gems/devise-3.2.2/app/views/devise/sessions/new.html.erb within layouts/application (34.5ms)
Completed 200 OK in 223ms (Views: 171.2ms | ActiveRecord: 5.8ms)
如何让Devise返回401 JSON错误?
答案 0 :(得分:4)
经过大量搜索,我找到了解决方案。
我为Devise添加了一个自定义失败应用程序:
class JsonFailureApp < Devise::FailureApp
def respond
self.status = 401
self.content_type = 'json'
self.response_body = '{"error" : "authentication error"}'
end
end
并将其添加到Devise:
config.warden do |manager|
manager.failure_app = JsonFailureApp
end
现在不会调用重定向,而是注册状态为401。
答案 1 :(得分:0)
首先,您需要配置devise以在API应用程序中工作。您可以按照此项目Wiki页面Configuring devise for APIs
中的说明进行操作