Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Access Token Security Concerns

What is the best practice for storing an access token in AngularJS after it is retrieved from an authorization server? I have seen many suggestions to use the localStorage service, but then I have read other posts/blogs that say to never use localStorage to store tokens, it is not secure etc.

I am having a hard time wrapping my head around security with Angular because of mixed information like above.

like image 1000
user3410575 Avatar asked Sep 05 '14 17:09

user3410575


1 Answers

I think,

  1. Generate the token (sensitive info at server side)
  2. Sign and Encrypt the generated token with machine key which is only known to server. And get the encrypted token.
  3. Then save the encrypted token obtained at step2 in cookies.
  4. Cookies expiration should be very less. Make httponly cookie.

When authenticating the cookie

  1. Validate the cookie
  2. Decrypt with machine key and verify it is sent by our server only and with the same crc.
  3. Authenticate the obtained token if step2 above is good.

Angularjs Automatically add headers in each $http request,

AngularAppFactory.GetApp=function(appName){
    var app = angular.module(appName,  []);

    app.factory('httpRequestInterceptor', ['$rootScope', function($rootScope)
    {
        return {
            request: function($config) {
             if( $rootScope.user.authToken )
             {
              $config.headers['id'] = $rootScope.user.id;
               $config.headers['auth-token'] = $rootScope.user.authToken;
             }

             return $config;
        }
    };
    }]);

    app.config(function ($httpProvider) {
      $httpProvider.interceptors.push('httpRequestInterceptor');
    });

    return app;
}



//Whenever you need to get new angular app, you can call this function.
app = AngularAppFactory.GetApp('appName');
like image 145
Ganesh Avatar answered Oct 15 '22 06:10

Ganesh