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

16,128

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
16,128
koo
Author by

koo

Software Engineer @Maps, Naver Corp

Updated on July 25, 2022

Comments

  • koo
    koo almost 2 years

    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.

  • Tudor
    Tudor almost 4 years
    in memory is not secure. If you can access localstorage from javascript, you can definitely access any in memory object so the cookies approach with 'same-site' I believe to be the best. However the development might be more painful since I don't know how well does postman cope with setting cookies across requests
  • human
    human almost 4 years
    In-memory must be of course secured by encapsulation, the ability to have that implementation makes it secure.
  • Tudor
    Tudor almost 4 years
    JS doesn't have private fields so there is no encapsulation. Sure ES2019 has that but it lacks browser support from many providers developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . If you go the Typescript way you do have private but that is also transpiled down to normal JS so the fields might still become available
  • chai
    chai over 2 years
    is this secure?