1

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!

NicuVlad
  • 2,491
  • 3
  • 28
  • 47
  • I guess, it depends on your overall architecture. I think the best thing is to read a couple of articles. This one helped me: https://www.sitepoint.com/user-authentication-mean-stack, because I am using the MEAN stack. There, the user data is stored inside the JWT (token). – alex351 Apr 11 '19 at 10:10
  • Does your Token process follow a standard authentication model like Oauth2 or OpenId? Actually those would be recommended. – MoxxiManagarm Apr 11 '19 at 10:28
  • @alex, thanks for the article! I will read it. – NicuVlad Apr 11 '19 at 11:16
  • @MoxxiManagarm, we use JWT. – NicuVlad Apr 11 '19 at 11:17

1 Answers1

1

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
yujinpan
  • 519
  • 3
  • 6