I'm implementing stateless REST API via Json Web Tokens (JWT). At the moment, I'm wondering what is the best approach to pass the user data to the front end. Those are the fields I would need to access on the front-end username, email, role, full_name, description, profile_img, facebook_id, twitter_id, custom_setting_1, custom_setting_2, custom_setting_3, custom_setting_4
There are 2 options that I see:
username, role
to JWT. After the JWT is created and returned to the front-end, I send another request for the user data from the API. I might be missing something here as well. So wondering what is the best approach handling the user data with JWT.
In your frontend, store the access token in memory of your client's JavaScript application and store the refresh token in a web store. Send JWT access token as a bearer in HTTP header with each server request that requires authorization. Verify the JWT on your server using the public key (public to your services).
Use cookies to store JWT tokens – always secure, always httpOnly, and with the proper same site flag. This configuration will secure your client's data, it will prevent XSS and CSRF attack and also should simplify web application, because you do not have to care about using tokens manually on frontend code anymore.
Once you are using JWT for authentication purposes (I understand your server is generating an authentication token that the client needs to send to the server in every request), there's not point in including all of those details in the token.
Your second approach makes much more sense:
I can add only unchangeable fields like
username
,role
to JWT. After the JWT is created and returned to the front-end, I send another request for the user data from the API.
Keep your JWT lean and perform another request to have the user details.
For more information on how to design the URL to return the authenticated user details, check below:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With