In my current project, I am using JWT to maintain session, I stored the user claims like profile image, firstname, lastname in the token. However, whenever I update the user, e.g. the username, or profile image, my JWT automatically becomes stale since it is still relying on the claims stored in it.
I thought of making idempotent request (PUT, PATCH, POST, DELETE) return a new JWT in addition to their original response, but I had to reject the idea for two reasons because
The alternative, was storing my JWT with minimal claims then on each page load, send a request to fetch the latest user object before populating the page, I have concerns about this because every load will hit the server at a minimum and possibly the database( though redis and a performant cache should alleviate the additional load).
What are the best practices in this situation?
Hi Adetola Onasanya ! Store minimum info in your JWT and do more requests to get fresh data. REST is scalable by its nature so you should not afraid of performance problems. Ensure your data is up to date, and then (if you get performance issues) you can easily solve them all.
Ideally your JWT shouldn't rely on dynamic information like that? I'm not sure how Laravel generates it's JWT, but I never have this kind of issue when I have to update user info.
If you're protecting routes, you should be hitting the API on every request to validate the token anyway (and caching with Redis when possible). So your alternative, despite seeming intensive, is the "best practice" to ensure tokens aren't faked.
If you need a workaround, I'd add a method to your User model that grabs the JWT token and add it to the response request (solving problem with SOLID principles - making adding a JWT relationship to Users). Allows you to get the token back easily on PUT/PATCH requests, along with the updated user profile. If your app depends on it and refreshes the token so often, this kind of functionality only makes sense and makes development easier.
SOLID or not, it sounds like you need it, and you can refactor to make it SOLID later.
Xingheng Wang
Co-founder Moesif.com (API analytics). Previous Microsoft & Zynga. CS from MIT.
few things on best practice. :
{ sub: "userid", permission: { profile: "read:write", resource1: "read", resource2: "write", service1: "read" } }The JWT token should always be short lived, so make sure
expis always set, or else you can't really revoke them.The claim should be self evident, ie. whole point of the JWT is so that each service don't have to check a centralized place like redis.