微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Google OAuth2 (Javascript/REST) 刷新令牌

如何解决如何使用 Google OAuth2 (Javascript/REST) 刷新令牌

我正在尝试从 Google OAuth2 获取新令牌,但我不断收到此错误

error message

这是我的代码(我使用 Expo 来构建 React Native 应用程序):

        const uri = 'https://oauth2.googleapis.com/token'
        const headerr = {
            'Content-Type': 'Content-Type: application/x-www-form-urlencoded'
        }
        const bodyy = {
            "client_id": '******************',"refresh_token": `${refreshToken}`,"grant_type":"refresh_token","access_type":"offline"
        }
        const fitnesss = await fetch(uri,{
            method: "POST",headers: headerr,body: JSON.stringify(bodyy)
        });
        fitnesss.json().then(res => {
            console.log(res)
        })

有人知道如何解决这个问题吗?

解决方法

不受支持的授权类型意味着您使用的语言不支持授权类型刷新令牌。

这样做的原因是 JavaScript 是客户端的,这意味着您需要在代码中包含刷新令牌。在浏览器中查看过源代码的任何人都可以看到并使用您的刷新令牌。

要使用刷新令牌,请使用服务器端语言。例如 Node.js

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/drive.metadata.readonly'];
// 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 Drive API.
  authorize(JSON.parse(content),listFiles);
});

/**
 * 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,token) => {
    if (err) return getAccessToken(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 getAccessToken(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,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);
    });
  });
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。