简体   繁体   中英

google access token expiring every 1h, how can I generate new one each time?

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!

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:

  1. Create authorization credentials.

  2. 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

  1. Create the authorization request

  2. Manually grant access to your application (only once).

  3. Get a refresh and access token.

  4. Use the refresh token to get a new access token when it expires.

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);
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM