AngularJS Access Token Security Concerns
Asked Answered
P

1

7

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.

Pinwheel answered 5/9, 2014 at 17:50 Comment(3)
What links do you have that suggest local storage is not a good idea?Entity
I don't have them handy, but will dig them up again. I am familiar with yours and Dominick's work and would love to hear your opinion on storing it in local storage. Is this something you would recommend?Pinwheel
I think local storage is fine, as long as you're aware of how it all works. In a sense, it's no different than a persistent cookie you're using for a website login.Entity
L
1

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');
Lempres answered 5/9, 2014 at 20:4 Comment(1)
I am trying to do just that. There are some implementation details I am missing. I have an asp.net mvc app that just handles login logic, sets an auth cookie, and then redirects to the angular app. The login logic involves calling a token endpoint on a web api on a different server. When I get that back I store that token in the cookie. But, how do I send that token back to the webapi from angular without manually putting it in an authorization header?Pinwheel

© 2022 - 2024 — McMap. All rights reserved.