英文:
How to fetch user's data after authentication in SPA?
问题
- 将用户令牌在前端解码以将这些值存储在Redux存储中是否是一种良好的做法?
- 也许我可以只在JWT的主体中发送userId以减少JWT中可用的数据。如果我这样做,我将需要以其他方式获取用户的其他数据,如用户名、电子邮件、头像等。对此我有两种可能的想法:
2.1) 我应该在身份验证响应的主体中发送用户的数据吗?这是一种良好的做法吗?
2.2) 或者在身份验证后,当我将用户重定向到主页时,我可以检查Redux存储是否具有用户字段(它是否为null),然后通过userId向REST API发出另一个请求以检索用户的数据。
哪种方法更好?
英文:
I'm new to React and building a SPA with a Express.js backend for some practice. I'm used to session based authentication and can't decide what's good and what's not good when it comes to authentication and security of SPA.
Upon authentication with valid user information, I issue a JWT token to client using Authorization header. Simply put, my question is about what to put in JWT's body and what to send in authentication request's response body and how to fetch user's data to show on header or store in Redux.
For now, I only provide userId, username, email values in JWT's body. These informations are not relatively sensitive in my opinion.
- Is it a good practice to decode the user's token on front-end after authentication to store these values in Redux store?
- Maybe I can only send userId in JWT's body to minimize the data available in JWT. If I do so, I will need to user's other data like username, email, avatar etc. in other ways. For that I have 2 possible ideas:
2.1) Should I send user's data in authentication response's body? Is it a good practice?
2.2) Or after the authentication when I redirect user to homepage I can check if Redux store has user fields (is it null) and make another request to REST API with userId to retrieve user's data.
Which of these a better approach?
答案1
得分: 1
当在前端解码JWT时,重要的是记住JWT负载是base64编码的,任何有权访问的人都可以轻松解码它。因此,在JWT负载中避免存储敏感信息至关重要,因为它有可能被暴露出来。考虑最小化JWT负载中可用的数据(例如,仅包括用户ID),您可以在身份验证后进行额外的API请求来检索用户的数据。
英文:
When decoding a JWT on the front-end, it's important to remember that the JWT payload is base64-encoded and can be easily decoded by anyone who has access to it. Therefore, it's crucial to avoid storing sensitive information in the JWT payload, as it can potentially be exposed.Consider minimizing the data available in the JWT payload (e.g., only including the user ID), you can make an additional API request to retrieve the user's data after authentication.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论