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
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!
I am dealing with this, I hope to help you.
api/login
repsonse like this:{
token: 'your token...',
expireAt: 'token expire time',
user: {
name: 'admin',
role: 'master'
// ... else user info
}
}
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.
cookie
should not save complex or large data structure, becase it: