如何在 angular.js 中使用令牌管理身份验证? [英] How to manage authentication with token in angular.js?

查看:35
本文介绍了如何在 angular.js 中使用令牌管理身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我创建了一个带有令牌身份验证的 RESTful API(Rails 4 + Devise),我还使用 gem(rack-cors) 管理 CORS 实现,但现在我想将 API 与 angular.js 一起使用

Hi Everyone I created a RESTful API with authentication with token (Rails 4 + Devise), Also I manage the CORS implementation with a gem(rack-cors) but now I would like use the API with angular.js

为此,我这样做:

var app = angular.module('models');

app.factory('Session',['$resource',function($resource){
    var Session = $resource(
        'http://api.creositios.dev/sessions/:id',
        {},
        {
            create: { method: 'POST'},
            delete: { method: 'DELETE', params: { id: '@id'} }
        }
    );
    return Session;
}]);  

这是我的控制器

app = angular.module('controllers');

app.controller('SessionCtrl',['$scope','Session',function($scope,Session){

  $scope.new_session =  function(){
    $scope.session = Session.create({email: 'developer.jimenez@gmail.com', password: '12345678'});
  };

}]);

到目前为止,我对实现没有问题.我的问题是不知道如何管理返厂的代币.

So far I have not problem with the implementation. My problem is have not idea how to management the Token that return my factory.

使用 angular.js 管理用户令牌并在 angular.js 中的不同控制器中验证用户的良好做法是什么?

What is the good practices for managment the token of user with angular.js and validates the user in the differents controllers in angular.js?

这是我的第一个使用令牌进行身份验证的应用程序.非常感谢您的建议!

This is my first app with authentication with token. Advice is very appreciate!.

推荐答案

一种常见的做法是将安全逻辑放在服务中,并使用 httpInterceptor 在您的请求中设置令牌.

A common practice is to put the security logic in a service and use an httpInterceptor to set the token in your requests.

安全服务.

angular.module('security')
    .factory('Security', ['$http', function ($http) {

        var token;

        function login(email, password) {
            return $http.post('/auth/login', {email: email, password: password})
                .then(function (response) {

                    if (response.data.token) {
                        token=response.data.token;
                    }
                });
        }

        function getToken(){
            return token;
        }

        return {
            login:login,
            token:getToken
        };     
}]);

这个特定的登录方法可以被登录控制器使用,例如:当用户登录时,返回的令牌被存储.

this particular login method could be used by a login controller for example: when the user login the token returned is stored.

现在您可以使用拦截器将令牌添加到所有 http 请求中

Now you can add the token to all your http requests with an interceptor

    .factory('authorizationInterceptor', ['Security', function (Security) {
        return {
            request: function (config) {
                var token=Security.getToken();
                config.headers = config.headers || {};
                if (token) {
                    config.headers.Authorization = 'Bearer ' + token;
                }
                return config;
            }
        };
    }]);

在引导应用程序时,不要忘记添加拦截器

When bootstraping the application, don't forget to add your interceptor

        .config(['$httpProvider',function ($httpProvider) {
            $httpProvider.interceptors.push('authorizationInterceptor');
        }]);

现在将在每个 http 请求上设置令牌,如果失败,则由您决定.

Now the token will be set on every http request, what you do with in case of failure then is up to you.

例如,您可以添加另一个响应拦截器,如果获得 401 或 403 响应重定向到登录页面等

For example you can add another response interceptor which if get 401 or 403 response redirect to the login page, etc

这篇关于如何在 angular.js 中使用令牌管理身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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