wrt https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ dont we have to ensure token belongs to same user ?
I see code has login to generate token (authenticate_user). on client side some where (localstorage in browser) it can be stored but then on server side its not mentioned where its stored. I would expect that for each user or some entity it should be stored in cache/db. so in create_user_token we need to store in db user:token mapping and in get_current_user we should also have some way to compare the token for user ? compare TokenData.username for request TokenData.username ?
so its left to user to implement it ? or am I misunderstanding and already implemented in example ?
regards,
miten.
>Solution :
You may use JWT token for validating user if you use verify signature flag when decoding a token. However it is crucial not to store any secret information in the payload, because it is easily accessible by the client. Also to note JWT doesn’t check the user agains your database. For example if you use user_id in the payload JWT doesn’t check that the user wasn’t deleted from the database on the server side.
JWT is the string that consist of three parts {part1}.{part2}.{part3}. Here part2 contains any payload that you want to hash in JWT. This data is not secured anyhow. However part3 is an securely encoded signature key and hash of the payload. JWT decodes part3 to check that whole payload was created on your server and wasn’t modified by user.