Sending JWT without Framework

Asked

Viewed 99 times

0

What is the best way, in terms of best practices and practicality, to simplify the process of moving a JWT?

I know that with Ionic or Angular, after configuring some module for JWT, the application starts to inject the token in all requests automatically, however, I want to do something similar without using them.

Through the article below, we can have the idea of how to implement JWT itself, however, it finishes the article only with token storage, need to understand how to model the next step without having to send the token manually in all requests.

https://jonathanmh.com/example-json-web-tokens-vanilla-javascript/

1 answer

1


In the example (link also inserted in question), the token is saved into a cookie, correct?

localStorage.setItem('token', token);

The next step is to implement a function that intercepts the request before it is sent and adds the token to the request header:

(function(send) {
    XMLHttpRequest.prototype.send = function(data) {
        var jwtToken = localStorage.getItem('token');
        if(jwtToken)
            this.setRequestHeader('Authorization', "Bearer " + jwtToken);
        send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);

What the above code does is to check for cookie identified by token.

var jwtToken = localStorage.getItem('token');
if(jwtToken)
//...

The cookie stores the JWT Token. If this value exists, then it will be injected into the header of the request, usually in the header Authorization.

this.setRequestHeader('Authorization', "Bearer " + jwtToken);

For more information, you can read the documentation, more precisely the section JSON Web Tokens work?

  • Thank you very much Filipe! Excellent, my doubt was in intercepting the requests

  • @Did Davidsilva’s answer help? Was the problem solved? If so, mark the answer as correct. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.