[英]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.几个月前我开始为 Angular 项目构建我的第一个基于令牌的身份验证,现在我需要升级它。 Until now my /login endpoint returned just a token which is stored in the local storage.
到目前为止,我的/login端点只返回一个存储在本地存储中的令牌。 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)?
我应该使用存储(本地存储/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: api/login
响应如下:{
token: 'your token...',
expireAt: 'token expire time',
user: {
name: 'admin',
role: 'master'
// ... else user info
}
}
Use localStorage
save the token and user info.使用
localStorage
保存令牌和用户信息。 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.下次打开同一个网站时,可以从本地存储中获取token信息,根据过期时间判断是否需要重新登录。
cookie
should not save complex or large data structure, becase it: cookie
不应该保存复杂或大型的数据结构,因为它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.