Reputation: 2290
I am working on a Google DialogFlow Api V2 and I find it somehow confusing how to properly deal with the authentication process.
I have already created service account key as a json file and then I run following command:
gcloud auth activate-service-account --key-file="credentials.json"
which is saying that it has activated then I run gcloud auth print-access-token
which would print me the access token and this token I can pass into the Header using the below code:
fetch(configs.baseUrl + "query?v=20150910", {
body: JSON.stringify({
queryInput: {
text: {
text: "Hello",
languageCode: "en-US"
}
}}),
headers: {
'content-type': 'application/json',
"Authorization": "Bearer xxxx",
},
method: 'POST',
})
.then(response => response.json())
.then(data => {
console.log(data.result);
})
.catch(error => console.error(error))
This would work perfercly fine for 1h until the token expires, the question is how do I re generate a new token since I already have the service-account-key-file.json can I somehow regenerate the access token from this information?
Using this client library https://github.com/dialogflow/dialogflow-nodejs-client-v2 works well I dont have to do anything about access token but the problem is I dont wanna use Node.js
Would it be possible so I can manage to get access token each time when expired using only javascript and the service-account-key-file.json I have generated.
I would appreciate the code samples!
Upvotes: 2
Views: 3049
Reputation: 1065
you can generate token by using following
import { dialogflowConfig } from './config/dialogflowConfig';
import { TokenCache } from 'google-oauth-jwt';
function generateAccessToken() {
return new Promise((resolve, reject) => {
const tokens = new TokenCache();
tokens.get({
// client_email from .json file
email: dialogflowConfig.client_email,
// private key from .json file
key: dialogflowConfig.private_key,
// you can put scope ['https://www.googleapis.com/auth/cloud-platform']
scopes: dialogflowConfig.scopes
}, function (err, token) {
if(err){
reject(err);
}
resolve(token);
});
});
}
Upvotes: 0
Reputation: 1576
Given the security implications of setting up a correct authentication process, it is recommended to use Client libraries whenever possible, for example, the NodeJS library.
However, if you want to implement this process on your own, you can take a look at this guide which explains how to set up OAuth 2.0 for Web Server Applications. The steps are as follows, you can find the HTTP/REST requests and responses examples in the guide:
Create authorization credentials.
Identify Access scopes: The resources your application needs to access, according to DialgoFlow API documentation, the required access scope is:
https://www.googleapis.com/auth/cloud-platform
Create the authorization request
Manually grant access to your application (only once).
Get a refresh and access token.
Use the refresh token to get a new access token when it expires.
Upvotes: 1