JWT token with AJAX, non-AJAX, JQuery

22,990

Solution 1

You need to store the token at client side using for example a cookie or localStorage

Ajax requests

  • Cookies: A cookie is sent automatically when making a request to the server, so you do not need to add a specific header

  • LocalStorage:It is needed to provide the token in each request using an HTTP header.

For example

POST /authenticatedService 
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

This is an example code to show how to execute an ajax POST request using jquery

$.ajax({
    type: "POST", //GET, POST, PUT
    url: '/authenticatedService'  //the url to call
    data: yourData,     //Data sent to server
    contentType: contentType,           
    beforeSend: function (xhr) {   //Include the bearer token in header
        xhr.setRequestHeader("Authorization", 'Bearer '+ jwt);
    }
}).done(function (response) {
    //Response ok. process reuslt
}).fail(function (err)  {
    //Error during request
});

Form submit

With a form submission you can not control the headers set by browser, so it is not possible to set the Authorization header with a Bearer token. In this case you can

  • Cookie: store the JWT in a cookie that will be sent with the form data. You will need to add extra security to avoid CSRF attachs
  • Form param: The JWT is stored in a hidden field of the form.

Use always POST (not GET) to avoid cache of JWT

Link

A link executes a GET request. You could build the link adding the JWT as a query param url?jwt=...

But, consider in this case the security risks. Browser can cache the url and it will be present in logs. An attacker could potentially obtain them if he has access. Also the user could copy the link and use it outside your web application (e.g send it by email...)

If you use cookies, the token will be automatically sent to the server by clicking on the link, but this will only work if the user is authenticated. In this case be aware of CSRF vulnerabilities

Solution 2

Your only option is to store the token in a cookie if you don't want to do anything suggested above. You can't set http headers in links.

Share:
22,990
supertorqued
Author by

supertorqued

Updated on July 05, 2022

Comments

  • supertorqued
    supertorqued almost 2 years

    I'm a bit frustrated with managing my JWT token during login, submits and redirects. Before I get started here's my technology stack just in case:

    JQuery/Html -> Node.Js -> Java Restful Services -> MySQL.  
    

    My java Restful services manages creating the JWT Token returning it to the Node.js layer which decides what to do with it and pass it on the the client. This all works wonderfully.

    To get the JWT token I'm making an ajax based authentication request to the Node middle tier, which authenticates and returns the token which is summarily crammed into localstorage on the client.

    Now I have no desire what so ever to make the entire site load off a single page through ajax, it's a complex site and doing that is just dumb! I need to forward and navigate to sub pages while carrying along the JWT token.

    Here's the question (finally)... How do send along the JWT token to the middle tier (node.js) without attaching it as a request or post parameter because that's a big no no? I can't seem to find a way to stuff it in the header associated with Bearer.

  • supertorqued
    supertorqued about 7 years
    I actually have this for my ajax requests, however the question is really what's the best way to handle non-ajax requests like clicking a menu item to navigate from one section of the site to another?
  • pedrofb
    pedrofb about 7 years
    Sorry, I did not read the last part of your question. See updated answer
  • supertorqued
    supertorqued about 7 years
    Thanks for the feedback, this is how I'm working to address the issue. I'm dynamically adding the token as a request parameter to the url through a click handler associated with a class on the link. On the node side I'm grabbing the token from the param, header or post variable as it comes in and moving forward with the logic. I figure that's at least a little more secure than just exposing it in the request or in JS.
  • pedrofb
    pedrofb about 7 years
    With links there are not many more alternatives. I suggest also using short expiration time and HTTPS