首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何刷新youtube-data-api v3的访问令牌

如何刷新youtube-data-api v3的访问令牌
EN

Stack Overflow用户
提问于 2022-05-24 07:47:06
回答 1查看 547关注 0票数 2

我使用youtube数据api的v3作为我的服务器。到目前为止,我能够通过从重定向获得代码来创建令牌。

代码语言:javascript
复制
                oauth2Client.getToken(req.query.code, function(err, token) {
                    if (err) {
                      console.log('Error while trying to retrieve access token', err);
                      return;
                    }
                    oauth2Client.credentials = token;
                    storeToken(token);
                    res.redirect("/channel");
                  });

我在本地存储这个令牌,但我有以下几个问题;

  1. 如何检查请求即将发出时此令牌是否有效?
  2. 如何通过使用刷新令牌获得新令牌(如果当前所拥有的令牌已过期)?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-24 08:13:58

了解令牌是否有效的最佳方法是使用它。在访问令牌的情况下,只需使用它进行调用即可。在刷新令牌的情况下,答案是相同的,使用它创建一个新的访问令牌。

node.js客户端库应该为您处理访问令牌的所有刷新。

第一次运行此代码时,将在TOKEN_PATH中创建包含用户同意的文件,这是刷新令牌。如果文件存在,它将用于根据需要创建一个新的访问令牌。

代码语言:javascript
复制
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/youtube'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Tasks API.
  authorize(JSON.parse(content), listConnectionNames);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72359051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档