DEV Community

Discussion on: How to Secure JWT in a Single-Page Application

Collapse
 
ecyrbe profile image
ecyrbe • Edited

Do not do this. This is wrong. Always put JWT in memory, never elsewhere. For the statement about user experience, continue reading.

You should not use jwt cookies with http.only, or whatever... this will force you to develop backend APIs that use cookies instead of bearer tokens...this make your APIs browser dependant. This is Bad, your APIs should be browser agnostic.

The solution can be to only use cookies for your autorisation endpoint (usually something like /login or /authorize ) to do single sign on if you want better user experience. This is a convenient way of doing sso, but there are other secured technologies not relying on cookies.
This authorisation endpoint should be the only endpoint using cookies. If it receives a valid cookie it returns a JWT to the caller else it will redirect the user to the authentication page. As simple as that.

All the other APIs should use the jwt stored in memory and passed as a bearer token. Nothing else.

Collapse
 
salmannotkhan profile image
Salman Shaikh

What if we specify both in middleware first check if authorization header exists or not and if not then check for cookies. so this way you can support both ways :)

Collapse
 
felixasante profile image
felix asante

I am also interested in your approach. if you can make your explanations clear, it will really help

Collapse
 
sparkydman profile image
Ugwuede Chigozie

Am interested in this your approach but I still don't get your explanation correctly. Please if you can create a snippet maybe in GitHub that will be appreciated. Thank you so much👏

Collapse
 
nhat_nam20 profile image
NhatNam20

I am interested in knowing the secured technologies are you mentioning!

Some comments have been hidden by the post's author - find out more