zero_coding zero_coding - 1 month ago 11
Javascript Question

Where to save JWT and how to use it

I am trying to implement JWT in my authentication system and I have questions about JWT.

For saving the token, I would use cookie but it is possible too, to use localstorage or sessionstorage,
what would be the best choice?

I have read about, that JWT protect the site from CSRF. I can not imaging that, how that would works.
Assume, I save the JWT token in the cookie storage, how would it then protect from CSRF?

Update 1

I saw some samples in internet like

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


How can I implement that, when I make a request to server with browser. I saw also too, that some implement the token in the address bar like:

http://exmple.com?jwt=token


If I would make a request via ajax, then I could set header with jwt:token and so I can read the token from header.

Update 2

In google chrome I installed Advanced REST client, look at picture

enter image description here

As you can see, I can set header with data. It is possible to set this headers data via javascript, when I am making a GET request to the server?

Answer

Look at this web site: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

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 folliowing 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>