Using JWT for Authorization in Node

[亡魂溺海] 提交于 2021-01-29 07:01:05

问题


So I've been following a Udemy course that uses POSTMAN to teach authentication, but I have been wonder how it works in an actual app that uses the browser. We are taught to store the JWT token with res.header('x-auth-token', token). And then when we try to access a route that is protected, we manually add the token in POSTMAN header and get the token with req.header('x-auth-token') on the server and verify the token.

But in a real app, I logged in using the browser and it did indeed set the header up with a token, but once I type in the URL to go into the restricted/authenticated required path, lets say /user/profile, it asks for me to log back in. Is the token not carrying over when I type in the new URL?

How do I get it so the token is carried around in the browser till it expires?


回答1:


Similar to how you manually add the token in every request with POSTMAN, your client side application needs to handle (Obviously in coordination with server side ) how you send the token to server. It will not be carried on every request automatically. You need to store the JWT token returned by the server.

If you store the JWT token in a cookie, then browser will send token every time you make a request. But it is also recommended to not use a cookie. Check various ways on how to store the JWT token in the client side and how to repeatedly add the token on every future requests until logout. There is also a concept of refresh token to get a new token in case the token is expired.

Check the below blogs to get more information. You can find other resources on the internet as well.

https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/

https://blog.nextzy.me/implementing-json-web-token-jwt-to-secure-your-app-c8e1bd6f6a29



来源:https://stackoverflow.com/questions/63644149/using-jwt-for-authorization-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!