koo
koo

Reputation: 4363

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

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.

Upvotes: 12

Views: 42012

Answers (4)

Hosseinreza
Hosseinreza

Reputation: 551

it's easy just Follow me


First of all you have to save the Token(or access token) to the local storage, in the login component when you are sending request for login do the below:

signin:function() {
        axios.post('http://Somthing/log-in/',{
            username: this.username,
            password: this.password,
        })
        .then( (response) => {
            
            let token = response.data.access;
            localStorage.setItem("SavedToken", 'Bearer ' + token);
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            (this.$router.push({name:'HomePage'}));
            
            })

So now the problem is whenever you refresh the Homepage you got 401 error and the solution is : just add this : { headers: { Authorization:localStorage.getItem('SavedToken') }} to the end of each request that need the Token in its header, like below:

 axios.get('http://Something/', { headers: { Authorization:localStorage.getItem('SavedToken') }})
        .then(response =>{
            //something
        })

Notice that the token that i used in this explanation was SIMPLEJWT , if you are using somthing else maybe you have to change 'Bearer' to somthing else.

Upvotes: 5

human
human

Reputation: 2441

  1. JWTs should never be stored in your localStorage
  2. In fact, they shouldn't even be stored in your cookies, unless you are able to implement very strict CSRF protection

Checkout this for motivation

  • JWT as an id_token is like your user credentials
  • JWT as an access_token is like your session token

One option is in-memory. Checkout this for a deep dive

Upvotes: 1

user12360925
user12360925

Reputation: 21

First you have to create or Generate Token through Jwt (jsonWebTokens) then either store it in local Storage or through Cookie or through Session. I generally prefer local storage because it is easier to store token in local storage through SET and retrieve it using GET method. and after retrieving it through get you can verify it through jwt and also authenticate it with bearer authentication..

And for headers add Authorization

fetch("/users", {
  method: "Get",
  headers: {
    "content-type": "application/json",
    Authorization: "Bearer" + localStorage.getItem("token")
  }

Upvotes: 2

TRomesh
TRomesh

Reputation: 4481

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));
   };

Upvotes: 8

Related Questions