2

I have a Node.js Express web application where a user can log in by posting his email address and password to a route /signin and when successful he receives a JWT token and stores it in his local storage.
I'm new to using JWT tokens for authorization and there's one thing I don't really understand how to do. How do I make sure that the user always send his JWT token with every request after a successful login?

I'm not using any front-end framework such as React or Vue.

Hallur A.
  • 299
  • 1
  • 3
  • 13
  • 1
    Do you use a library like axios or jquery to perform these requests? – Ioannis Papadopoulos Jul 23 '18 at 12:38
  • Nope. The request is sent directly from the browser by the user. For example, the user could request example.com/profile which should be protected. @JohnPapadopoulos – Hallur A. Jul 23 '18 at 12:45
  • 1
    Have you considered storing the jwt in a cookie instead of localstorage? Then it would be included in the request. Check some resources on jwt storing methods too https://stackoverflow.com/questions/34817617/should-jwt-be-stored-in-localstorage-or-cookie – Ioannis Papadopoulos Jul 23 '18 at 12:51

3 Answers3

3

You would need to send HTTP headers on every protected requests. The JWT token would be carried by the Authorization header like so:

Authorization: Bearer efh1340ufeileaf3148913-your-token

Then your backend would check if the token is valid and not expired and grant access to the data/route etc.

Take a look at https://jwt.io/introduction/, https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication and many many more on the subject

t3__rry
  • 2,817
  • 2
  • 23
  • 38
  • But how would I set the Authorization header if the user requests the protected route directly from the browser? – Hallur A. Jul 23 '18 at 12:48
  • 2
    _The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method_: https://stackoverflow.com/questions/581383/adding-custom-http-headers-using-javascript – t3__rry Jul 23 '18 at 12:49
0

Use Jquery Ajax

$.ajax({
    type: "POST", //Any CRUD Op
    url: 'url'  //the url to call
    data: datatosend,     
    contentType: contentType,           
    beforeSend: function (xhr) {   //Include the bearer token in header
        xhr.setRequestHeader("Authorization", 'Bearer '+ jwt);
    }
},
success: function(){
    //Your success code
}
)
sairohith
  • 272
  • 2
  • 9
0

Storing the JWT in a cookie instead of in the local storage did the trick. Thanks to @JohnPapadopoulos for the suggestion :)

Hallur A.
  • 299
  • 1
  • 3
  • 13