简体   繁体   English

前端客户端的用户对象

[英]User object on client side in front-end

I am developing a back-end API in Node.js using Express.js framework and implemented JWT authentication using Passport.js .我正在使用Express.js框架在Node.js开发后端 API,并使用Passport.js实现 JWT 身份验证。

Users register, sign in using their usernames and passwords and receive a json web token generated in back-end which then is used to authenticate further requests.用户注册,使用他们的用户名和密码登录并接收在后端生成的 json Web 令牌,然后用于验证进一步的请求。

What I want to achieve is to always display a piece of current user information in the front-end while user is logged in. That information is subject to frequent changes based on the user or even other users interaction with the API.我想要实现的是在用户登录时始终在前端显​​示一条当前用户信息。该信息会根据用户甚至其他用户与 API 的交互而频繁更改。

What is the common technique for this?这有什么常用的技术? Should I send a user object with every response from the API or should I send it once as the payload in the JWT, store it on the client side and update it on demand with separate requests to some user API endpoint?我应该在来自 API 的每个响应中发送一个用户对象,还是应该将它作为 JWT 中的有效负载发送一次,将其存储在客户端并根据需要使用对某些用户 API 端点的单独请求进行更新?

Actually, can JWT payload even be used for storing such things as user objects, is it intended for this?实际上,JWT 负载甚至可以用于存储诸如用户对象之类的东西,它是为此而设计的吗? As I feel it is a bad idea to store some important information other than some user identifier in the JWT payload.我觉得在 JWT 负载中存储一些重要信息而不是一些用户标识符是一个坏主意。

A JWT is valid until expiration time. JWT 在到期之前一直有效。 Including data in the token that change frequently means that the JWT could be invalid, but it would be accepted anyway by your server.在令牌中包含频繁更改的数据意味着 JWT 可能无效,但无论如何您的服务器都会接受它。 If you do not want to deal with blacklists consider carefully what data are you going to include and request dinamycally the other data.如果您不想处理黑名单,请仔细考虑您将包含哪些数据并以动态方式请求其他数据。

But, without including any user data into the token you are not taking profit of one of the JWT advantages: the server does not need to query database in each request, since you can trust in data contained in JWT.但是,如果不将任何用户数据包含在令牌中,您就无法利用 JWT 的优势之一:服务器不需要在每个请求中查询数据库,因为您可以信任 JWT 中包含的数据。

Eg you can include fullname or dateofbirth and consider to include roles if they do not change frequently例如,您可以包含fullnamedateofbirth并考虑包含不经常更改的roles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM