javascriptweb-servicessecuritycookiesjwt

Where to save a JWT in a browser-based application and how to use it


I'm trying to implement JWT in my authentication system and I have a few questions. To store the token, I could use cookies but it's also possible to use localStorage or sessionStorage.

Which would be the best choice?

I have read that JWT protects the site from CSRF. However, I can't imagine how that would work assuming I save the JWT token in cookie storage.

How would it then protect from CSRF?

Update 1
I saw some usage samples like the following:

curl -v -X POST -H "Authorization: Basic VE01enNFem9FZG9NRERjVEJjbXRBcWJGdTBFYTpYUU9URExINlBBOHJvUHJfSktrTHhUSTNseGNh"

How can I implement that when I make a request to server from the browser? I also saw that some implement the token in the URL:

http://exmple.com?jwt=token

If I would make a request via AJAX then I could set an header like jwt: [token] and then I could read the token from header.

Update 2

I installed the Advanced REST Client Google Chrome extension and was able to pass the token as a custom header. Is it possible to set this header data via Javascript when making a GET request to the server?


Solution

  • *[EDIT] This answer is the accepted one, however the response from João Angelo is way more detailed and should be considered. One remark though and because the security pratices evolved since Nov. 2016, the Option 2 should be implemented in favour of the Option 1.

    If you want to store them, you should use the localStorage or sessionStorage if available or cookies. You should also use the Authorization header, but instead of Basic scheme, use the Bearer one:

    curl -v -X POST -H "Authorization: Bearer YOUR_JWT_HERE"
    

    With JS, you could use the following code:

    <script type='text/javascript'>
    // define vars
    var url = 'https://...';
    
    // ajax call
    $.ajax({
        url: url,
        dataType : 'jsonp',
        beforeSend : function(xhr) {
          // set header if JWT is set
          if ($window.sessionStorage.token) {
              xhr.setRequestHeader("Authorization", "Bearer " +  $window.sessionStorage.token);
          }
          
        },
        error : function() {
          // error handler
        },
        success: function(data) {
            // success handler
        }
    });
    </script>