O'Reilly logo

Mastering Internet of Things by Peter Waher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using tokens in JavaScript

Now that our web services are protected, we need to update our JavaScript to match this change. We begin by getting the current session token, as follows:

var SessionToken = null; 
 
function GetSessionToken() 
{ 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function () 
    { 
        if (xhttp.readyState == 4) 
        { 
            if (xhttp.status == 200) 
            { 
                SessionToken = xhttp.responseText; 
                window.setInterval(RefreshGauge, 2000); 
            } 
 
            delete xhttp; 
        } 
    }; 
 
    xhttp.open("POST", "/GetSessionToken", true); 
    xhttp.send(""); 
} 
 
GetSessionToken(); 

When we have the token, we only need to add it to requests being made, using the BearerAuthorization header, to pre-empt the WWW-authentication step, as follows:

xhttp.open("GET", "/Momentary", true); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required