How to manage authentication with token in angular.js?

我与影子孤独终老i 提交于 2019-12-04 15:02:02

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

security service.

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.

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');
        }]);

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!