Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store jwt token in localStorage and send it back to the server with header in express?

Tags:

express

jwt

I have read many articles in stackoverflow and have seen lots of youtube videos, but failed to find the example code which is demonstrating about the flow of saving jwt to localstorage - send back to server with authorization header for verifying.

Here is what I want to do.

When the client logs in to the server, server gives token and saves it to the client localStorage (or sessionStorage).

Whenever the client calls an api which can be accessed only with the token, client retrieves the token back from the localStorage, and send that token with the authorization header (req.headers.[x-access-token] or req.headers.[authorization]) to the server.

But all of the articles I've been read is explaining this issue with the Postman which does not show how to store it to the localStorage and put it in the authorization header.

Do I have to use localStorage.setItem when the server gives the token to the client, and use and localStorage.getItem and new Headers() with append() or axios before sending that token back to the server?

Examples don't have to be for the express user, but I'd like to get the glimpse of ideas.

like image 604
koo Avatar asked Apr 11 '19 11:04

koo


People also ask

Can we store JWT token in LocalStorage?

A JWT needs to be stored in a safe place inside the user's browser. Any way,you shouldn't store a JWT in local storage (or session storage). If you store it in a LocalStorage/SessionStorage then it can be easily grabbed by an XSS attack.

How do I send JWT tokens back?

We can send this token to other endpoints. This can be done easily. We have to add an authorization header in our request and this will be a Bearer TOKEN. To avoid any manual copy-pasting of JWT token, we can use variables to add a script in the Tests tab of API request which is generating token.

Where does JWT token go in header?

The first option is to add a header. Under the Headers tab, add a key called Authorization with the value Bearer <your-jwt-token> . Use the double curly brace syntax to swap in your token's variable value.


1 Answers

You can store your jwt token in localstorage and when ever you make a API call you can add the token to headers as token. if you are using axios you can attach you token to headers like this. Here the token is stored in localstorage with the key 'jwtToken'

  axios.post('http://yourendpoint',data,{ headers: { Authorization:localStorage.getItem('jwtToken') } })
            .then(response=> console.log(response))
            .catch(error => console.log(error));
   };
like image 84
TRomesh Avatar answered Oct 05 '22 06:10

TRomesh