angularangular7http-token-authentication

Angular token based authentication, get and store the user profile, best practice


I started some months ago to build my first token-based authentication for an Angular project and now I need to upgrade it. Until now my /login endpoint returned just a token which is stored in the local storage. The user is logged in when the token is present and valid. But now I need also to display the username in the navigation bar and the user role because I need to create a role guard.

I read a lot of articles and questions/answer about this topic but I'm really confused which is the best way to get the user profile.

Get

  1. Get the user details directly at the login together with the token
  2. Exactly after login, if login request is successful, execute another request for example: /me
  3. Add the username and the role in the token payload

Store

Also the details should be persistent(if the user close and open the browser), How can I store them? Should I use the a storage(local storage/cookie)? Or execute a request each time when the user open the application?

Use

Here I don't have any clue. If I use the storage, should I read them every time? Or should I use a subject?

From your experience which is the best way to do it? Or do you have other ideas? Thanks in advance!


Solution

  • I am dealing with this, I hope to help you.

    1. The api/login repsonse like this:
    {
      token: 'your token...',
      expireAt: 'token expire time',
      user: {
        name: 'admin',
        role: 'master'
        // ... else user info
      }
    }
    
    1. Use localStorage save the token and user info. You can get the token info from local storage when you open the same website in next time, and determine if you need to re-login based on the expiration time.

    2. cookie should not save complex or large data structure, becase it:

      • Inconvenient operation
      • Size is limited
      • Every time http request has to take