2

I am a beginner and recently started learning about authorization and authentication.

So i came across JWT and started looking for tutorials how to implement it in node js. Appearantly there is a jwt middleware for nodejs called "jsonwebtoken".

I have watched some videos about it and learned that you can access the created token by accessing the header: (req.headers) Video I got the information from

code

now I'm dealing with the problem where that "header" is coming from and where it is stored. Is it a html header or a specefic cookie. I know there are 3 storages (local, session and cookie storage) but in what of these 3 is it stored.

I am really confused

2 Answers2

3

You're the one who choose where to store it: after a successful authentication, JWT is meant to be sent to client and stored on client side, so as you said, you should choose between 3 solutions:

1- LocalStorage

2- Cookie: Vulnerable to csrf attacks.

3- SessionStorage: This option is excluded, because as soon as your user will close its window, data stored here will be lost, unless you want that behaviour.

Once your token has been stored, you can Again choose how to send it:

1- Send it in a header (Authorization) for example,

2- Send it directly in request body (in a JSON for example).

Your backend is then supposed to know how to extract it, from header / body, your choice again.

Keep in mind that you need to send it on every request you make to a protected area, that way you're making a stateless authentication everytime your backend receives a request to a protected area.

millenion
  • 1,218
  • 12
  • 16
  • Thank you really much for taking time to help me. But hoe exactly do i make those responses to the client in the http header ? [link](https://stackoverflow.com/questions/63230599/how-to-set-the-http-authorization-header-value) – AJ.beProgramming Aug 15 '20 at 16:19
1

In simple terms, after generating the token, you send it as a response either through a cookie (preferably http-only cookie if you want to avoid XSS attacks), or just send it in the response body, after which it is stored in the localStorage(or cookie if you opted to use that), and sent in the consequent HTTP requests with the Authorization header, whose value is bearer <token>, where is the jwt stored in the localStorage.

lanxion
  • 1,350
  • 1
  • 7
  • 20
  • Thank you really much for taking time to help me. But hoe exactly do i make those responses to the client in the http header ? [link](https://stackoverflow.com/questions/63230599/how-to-set-the-http-authorization-header-value) – AJ.beProgramming Aug 15 '20 at 16:20
  • 1
    the responses to the client is in the response body. The subsequent requests are sent via the header. depending on what you are using for sending requests from client (XHR/fetch/axios), you will have a way of adding a header to the request. A good approach would be to set up interceptors(if you use axios). – lanxion Aug 15 '20 at 16:47