简体   繁体   中英

Token Based Authentication AngularJS

I am new to AngularJS. What I want is getting a token coming from a server with $http post and then use that token coming from the request to use as an authorization header for access in other page and following data requests to the server. Here is my existing code:

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 I am aware that this can be done by using the .run like this:

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

However the token Authorization will be coming from a login authentication via post request

Step 1

Take the token from login response and save it somewhere in the app, most common solution is to store it in local storage so it will be available after browser restart.

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

    }

Step 2

Use angularjs $http interceptor to automatically add authentication header to every http request:

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

Or put it manualy every time you make http request:

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

More info: here and my angular webapi project

Already solved it. The solution is to store the token in a localstorage first then use run function for it be a default. Here is the code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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