I'm a software engineer working as a full-stack developer using JavaScript, Node.js, and React. I write about my experiences in tech, tutorials, and share helpful hints.
Awesome post, I have been looking into authentication like this and this answered most of the pending questions I had around how to keep it secure. Some other resources that I have looked at were vague on this.
I had a question on this:
No. Instead, the backend should set the JWT as a cookie in the user browser.
Hey, Ryan! Thank you for the kind words, I'm glad to have added some value!
That's the HTTP standard to set the cookie on the response request. It's likely that your backend has a wrapper for this - as in nodejs. This way we don't have to worry about HTTP standards, use a more friendly API instead.
This helps to prevent CSRF attacks but is exposed to frontend JS. Using the SameSite in your cookie will help against CSRF anyway.
In case you're worried, use both. You can have your main JWT set as a cookie, and a second JWT set in the Authorization header (may even use a different secret). The second one doesn't even have to contain the same info, perhaps only the user ID.
Then your backend can decode and validate both on each request. Doesn't add too much overhead and comes with an extra security layer. 😉
I'm a software engineer working as a full-stack developer using JavaScript, Node.js, and React. I write about my experiences in tech, tutorials, and share helpful hints.
Awesome post, I have been looking into authentication like this and this answered most of the pending questions I had around how to keep it secure. Some other resources that I have looked at were vague on this.
I had a question on this:
Would it just use the Set-Cookie Response Header or is there a different method?
Thanks!
Hey, Ryan! Thank you for the kind words, I'm glad to have added some value!
That's the HTTP standard to set the cookie on the response request. It's likely that your backend has a wrapper for this - as in nodejs. This way we don't have to worry about HTTP standards, use a more friendly API instead.
Some suggest sending the JWT in the Authorization header:
This helps to prevent CSRF attacks but is exposed to frontend JS. Using the SameSite in your cookie will help against CSRF anyway.
In case you're worried, use both. You can have your main JWT set as a cookie, and a second JWT set in the
Authorization
header (may even use a different secret). The second one doesn't even have to contain the same info, perhaps only the user ID.Then your backend can decode and validate both on each request. Doesn't add too much overhead and comes with an extra security layer. 😉
That makes sense, thank you!