繁体   English   中英

基于令牌的身份验证AngularJS

[英]Token Based Authentication AngularJS

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

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

    }
});

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

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

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

第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());
}

更多信息: 这里我的Angular Webapi项目

已经解决了。 解决方案是先将令牌存储在本地存储中,然后使用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;
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM