Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store authentication bearer token in browser cookie using AngularJS

I have created a bearer token using ASP.net Identity. In AngularJS I wrote this function to get authorized data.

$scope.GetAuthorizeData = function () {
  $http({
    method: 'GET',
    url: "/api/Values",
    headers: { 'authorization': 'bearer <myTokenId>' },
  }).success(function (data) {
    alert("Authorized :D");
    $scope.values = data;
  }).error(function () {
    alert("Failed :(");
  });
};

So I want to store this token into Browser cookies. If this token is present there , then take the token and get the data from IIS server Otherwise redirect to login page to login to get a new token.

Similarly, if user click onto log out button, it should remove the token from browser cookie.

How to do this ? It it possible ? Is it proper way to authenticate and authorize a user ? What to do if there are multiple users token ?

like image 787
Bimal Das Avatar asked Dec 31 '15 11:12

Bimal Das


People also ask

How do I store JWT in HTTP only cookies?

HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application.

Where should we store JWT token in angular?

A practical place to store the JWT is on Local Storage, which is a key/value store for string values that is ideal for storing a small amount of data.


1 Answers

There is a $cookies service available in the AngularJS API using the ngCookies module. It can be used like below:

function controller($cookies) {
    //set cookie
    $cookies.put('token', 'myBearerToken');

    //get cookie
    var token=$cookies.get('token');

    //remove token
    $cookies.remove('token');
}
controller.$inject=['$cookies'];

For your case it would be:

//inject $cookies into controller
$scope.GetAuthorizeData = function () {
    $http({
        method: 'GET',
        url: "/api/Values",
        headers: { 'authorization': 'bearer <myTokenId>' },
    })
    .success(function (data) {
        $cookies.put('token', data);
    }).error(function () {
        alert("Failed :(");
    });
};

You will also have to add the angular-cookies module code. And add it to your angular app: angular.module('myApp', ['ngCookies']);. Docs for Angular Cookies.

I would also like to suggest the usage of a Http interceptor which will set the bearer header for each request, rather than having to manually set it yourself for each request.

//Create a http interceptor factory
function accessTokenHttpInterceptor($cookies) {
    return {
        //For each request the interceptor will set the bearer token header.
        request: function($config) {
            //Fetch token from cookie
            var token=$cookies.get['token'];

            //set authorization header
            $config.headers['Authorization'] = 'Bearer '+token;
            return $config;
        },
        response: function(response) {
            //if you get a token back in your response you can use 
            //the response interceptor to update the token in the 
            //stored in the cookie
            if (response.config.headers.yourTokenProperty) {
                  //fetch token
                  var token=response.config.headers.yourTokenProperty;

                  //set token
                  $cookies.put('token', token);
            }
            return response;
        }
    };
}
accessTokenHttpInterceptor.$inject=['$cookies'];

//Register the http interceptor to angular config.
function httpInterceptorRegistry($httpProvider) {
    $httpProvider.interceptors.push('accessTokenHttpInterceptor');
}
httpInterceptorRegistry.$inject=['$httpProvider'];

//Assign to module
angular
    .module('myApp')
    .config(httpInterceptorRegistry)
    .factory('accessTokenHttpInterceptor', accessTokenHttpInterceptor)

Having the http interceptor in place you do not need to set the Authorization header for each request.

function service($http) {
    this.fetchToken=function() {
        //Authorization header will be set before sending request.
        return $http
            .get("/api/some/endpoint")
            .success(function(data) {
                 console.log(data);
                 return data;
            })
    }
}
service.$inject=['$http']

As stated by Boris: there are other ways to solve this. You could also use localStorage to store the token. This can also be used with the http interceptor. Just change the implementation from cookies to localStorage.

function controller($window) {
    //set token
    $window.localStorage['jwt']="myToken";

    //get token
    var token=$window.localStorage['jwt'];
}
controller.$inject=['$window'];
like image 61
cbass Avatar answered Oct 30 '22 22:10

cbass