【问题标题】:Token Based Authentication AngularJS基于令牌的身份验证AngularJS
【发布时间】:2016-02-23 09:21:35
【问题描述】:

我是 AngularJS 的新手。我想要的是从带有 $http post 的服务器获取令牌,然后使用来自请求的令牌用作授权标头,以便在其他页面中访问并跟踪对服务器的数据请求。这是我现有的代码:

var peopleApp = angular.module('peopleApp', ['ngRoute', 'ngAnimate']);


peopleApp.config(function($interpolateProvider, $httpProvider) {
    // Change template tags
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');

    // Enabling CORS
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    // $httpProvider.defaults.withCredentials = true;
});

peopleApp.controller('formController', function($scope, $http, $location) {
    $scope.logIn = function(json, url){
        $http.post(url, json)
        .then(function(response){
            token = response.data.token;
            window.location.href = 'crew-menu';
        },function(response){
            alert('Please check the following validations on the next alert and contact the creators regarding this error');
            alert(JSON.stringify(response.data.errors));
        });

    }
});

附: 我知道这可以通过使用 .run 来完成,如下所示:

peopleApp.run(function($http) {
     $http.defaults.headers.common.Authorization = 'YmVlcDpib29w';
});

但是令牌授权将来自通过发布请求的登录身份验证

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    第 1 步

    从登录响应中获取令牌并将其保存在应用程序的某个位置,最常见的解决方案是将其存储在本地存储中,以便在浏览器重新启动后可用。

    $scope.logIn = function(json, url){
            $http.post(url, json)
            .then(function(response){
                localStorageService.set('authorizationData', { token: response.data.token });
    
                window.location.href = 'crew-menu';
            },function(response){
                alert('Please check the following validations on the next alert and contact the creators regarding this error');
                alert(JSON.stringify(response.data.errors));
            });
    
        }
    

    第 2 步

    使用 angularjs $http 拦截器自动为每个 http 请求添加认证头:

    app.factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
    
        var authInterceptorServiceFactory = {};
    
        var _request = function (config) {
    
            config.headers = config.headers || {};
    
            var authData = localStorageService.get('authorizationData');
            if (authData) {
                config.headers.Authorization = 'Bearer ' + authData.token;
            }
    
            return config;
        }
    
        var _responseError = function (rejection) {
            if (rejection.status === 401) {
                $location.path('/login');
            }
            return $q.reject(rejection);
        }
    
        authInterceptorServiceFactory.request = _request;
        authInterceptorServiceFactory.responseError = _responseError;
    
        return authInterceptorServiceFactory;
    }]);
    

    或者每次发出http请求时手动输入:

    function buildConfig() {
        var c = {};
        var authData = localStorageService.get('authorizationData');
        if (authData) {
            c.headers.Authorization = 'Bearer ' + authData.token;
        }
    
        return c;
    }
    function post(url, model) {
        return $http.post(url, model, buildConfig());
    }
    

    更多信息:heremy angular webapi project

    【讨论】:

    • 这也是一个很好的解决方案。但我采用了 $window.localstorage 方法。检查我上面的答案。
    【解决方案2】:

    已经解决了。解决方案是先将令牌存储在本地存储中,然后使用 run 函数,因为它是默认值。代码如下:

    var peopleApp = angular.module('peopleApp', ['ngRoute', 'ngAnimate']);
    
    
    peopleApp.config(function($interpolateProvider, $httpProvider) {
        // Change template tags
        $interpolateProvider.startSymbol('[[');
        $interpolateProvider.endSymbol(']]');
    
        // Enabling CORS
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
        // $httpProvider.defaults.withCredentials = true;
    });
    
    peopleApp.controller('formController', function($scope, $http, $location, $window) {
        $scope.logIn = function(json, url){
            $http.post(url, json)
            .then(function(response){
                token = response.data.token;
                $window.localStorage.token = token;
                window.location.href = 'crew-menu';
            },function(response){
                alert('Please check the following validations on the next alert and contact the creators regarding this error');
                alert(JSON.stringify(response.data.errors));
            });
    
        }
    });
    
    peopleApp.run(function($window, $http){
        if ($window.localStorage.token){
            $http.defaults.headers.common.Authorization = "Token "+$window.localStorage.token;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 2016-01-23
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2017-07-10
      相关资源
      最近更新 更多