问题
I'm creating JWT authentication and I have some doubts:
to increase the security, could be a good idea save in database the user's token and check, everytime, if the token sent by API matches with the one saved into database? Is it really useful?
to avoid saving user info in session, is it a good idea puts email, if he is admin, etc in JWT's payload?
if I save the user info in JWT's payload, and the user change his email or other info, how could I update automatically the user's token saved in his browser?
it's better save the token as cookie or web storage?
回答1:
to increase the security, could be a good idea save in database the user's token and check, everytime, if the token sent by API matches with the one saved into database? Is it really useful?
This defeats the object of using JWTs at all. JWTs have the advantage that you don't have to track sessions server-side - they are purely client-side. JWTs have the disadvantage that you can't revoke tokens because of this (the price you pay). If you want the extra security, don't use JWTs and track sessions server-side using a random token (CSPRNG, 128bit).
to avoid saving user info in session, is it a good idea puts email, if he is admin, etc in JWT's payload? if I save the user info in JWT's payload, and the user change his email or other info, how could I update automatically the user's token saved in his browser?
Well you could use a user identifier instead of email. For example, the primary key of your user table. Then if they update their information the token is still valid. You should set short expiry dates, so if the user is no longer an admin they will have to request a new token (often called a refresh token) and the new token will not have the admin claim.
it's better save the token as cookie or web storage?
Up to you. If stored in a cookie it is sent with every request. If you'd prefer to retrieve the value with JavaScript, then use web storage. If using a cookie, set the Secure flag to prevent it leaking over plain HTTP, and the HttpOnly flag to secure it from any XSS vulnerabilities on your domain. Web storage cannot be secured against XSS in the same way (you need to make damn sure the whole of your domain is protected), however it is less likely to be leaked over plain HTTP.
回答2:
Similar to the response from @SilverlightFox - notice that you could require the database check for refresh tokens but not access tokens. That way you can tune the duration as you wish to make a tradeoff of security and efficiency
来源:https://stackoverflow.com/questions/35728065/best-way-to-implement-jwt