【问题标题】:How to Refresh Token Using Google OAuth2 (Javascript/REST)如何使用 Google OAuth2 (Javascript/REST) 刷新令牌
【发布时间】:2021-07-13 14:32:36
【问题描述】:

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

这是我的代码(我正在使用 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)
        })

有人知道怎么解决吗?

【问题讨论】:

    标签: oauth-2.0 google-api google-oauth google-fit


    【解决方案1】:

    不支持的授权类型表示您使用的语言不支持授权类型刷新令牌。

    这样做的原因是 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, (err, 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, (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);
        });
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2013-10-01
      • 2016-08-03
      • 2018-02-27
      • 2023-04-02
      • 2017-05-29
      • 2021-08-27
      • 2022-06-19
      相关资源
      最近更新 更多