简体   繁体   中英

Best practise attaching token to request header in token based authentication

I am using AngularJS with token based authentication and would like to know what is your opinion on best practise with maintaining a persistant 'session' for the user by attaching a token to header requests. Let me describe the problem I've run into:

This is how it is setup right now, but slightly simplified:

  1. User signs in
  2. backend returns user object that contains a token, user is considered signed in and token is saved in local storage
  3. user refreshes page, page is loaded and angular is initialized, no user object and token is returned and user is not considered signed in for the moment being as no token was automatically attached to user's request
  4. now as soon as angular is initialized it checks for existance of token in localstorage and if found makes a GET request to backend with token attached to the request by using a httpInterceptor, user object with token returned and token refreshed, user is again considered signed in

What I would like to know is how to avoid momentary flash of user being signed out in step 4. With cookie based authentication this is possible because the cookie is automagically attached to every request so my backend can deserialize the cookie before it returns a rendered template in response and attach a user object to that rendered template in json format within a script tag which angular can then access and load when it initializes resulting in no delay.

The problem with token is that while it exists on the client's localStorage, it is not attached to the request automagically when the page is refreshed. It is only attached when the user makes a http request AFTER angular has initialized and it has lodaded its httpInterceptor that attaches this extra header field with token included.

So is it possible to always automatically attach the token stored in localStorage to the header of every request or is my current approach as good as it gets. I guess I could store the token in a cookie but that would really defeat the purpose of token based authentication I think.

Am I approaching this incorrectly ?

In my opinion your approach is right, but you should check for the token and refresh it during a service initialization called in resolve phase of your routes . This should prevent the initial flash

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