Sending JWT without Framework

0

What is the best way, in terms of good practices and practicality, to simplify the process of trafficking 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 get the idea of how to implement JWT itself, however, it ends the article only with token storage, I need to understand how to model the next step without having to manually send the token to all the requisitions.

link

    
asked by anonymous 01.03.2018 / 21:44

1 answer

1

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

localStorage.setItem('token', token);

The next step is to implement a function that intercepts request before it is sent and adds the token in 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 check to see if there is 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 documentation , specifically the JSON Web Tokens work?

    
02.03.2018 / 19:37