I found this example on the official site of DialogFlow using Node.js and it is working fine, but I dont know how do I integrate this into my web application.
Is it
As others have said here before, the access token has a duration of one hour, after that time it becomes useless. So it's necessary to make a call (http call in my case) to the API in order to request an access token, one time each hour, and use it as explained by Satheesh thereafter. Instructions on how to generate the signature to make the call and use it later are given in https://developers.google.com/identity/protocols/OAuth2ServiceAccount.
Once you obtain the json file from the service account with the private key and the email you have to use (not your email, but the one generated by the service account), you can use the jsrsasign library (in pure javascript), that you can find in https://github.com/kjur/jsrsasign, to generate the JSON Web Signature (JWS) and thus the JSON Web Token (JWT), that will be needed to make the http call to get the access token.
Then you use it as described above by Satheesh to make the call to Dialogflow V2 via jQuery.
The code I have used to achieve this is the next one:
function _genJWS() {
var header = '{"alg":"RS256","typ":"JWT"}';
var claimSet = jwtClaimSet();
var privateKey = jwtPrivateKey();
var sHead = newline_toDos(header);
var head = KJUR.jws.JWS.readSafeJSONString(sHead);
var sPayload = newline_toDos(claimSet);
var sPemPrvKey = privateKey;
var jws = new KJUR.jws.JWS();
var sResult = null;
try {
prv = KEYUTIL.getKey(sPemPrvKey);
sResult = KJUR.jws.JWS.sign(head.alg, sHead, sPayload, prv);
} catch (ex) {
alert("Error: " + ex);
}
return sResult;
}
function _requestAccessToken() {
var access_token = accessToken;
var assertion = _genJWS();
console.log('Assertion: ' + assertion);
jQuery.ajax({
type: "POST",
url: "https://www.googleapis.com/oauth2/v4/token",
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + assertion,
success: function(response) {
console.log("success");
console.log(response);
access_token = response.access_token;
console.log(access_token);
},
error: function() {
console.log("Error");
}
});
return access_token;
}
Then use that access token to make the HTTP call to Dialogflow.
Hope it helps.