0

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

    }
});

P.S. 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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good solution too. But I did the $window.localstorage approach. Check my answer above.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.