【问题标题】:OAuth exchange giving invalid_grant and Bad requestOAuth 交换给出 invalid_grant 和 Bad request
【发布时间】:2018-06-08 02:20:03
【问题描述】:

尝试将 OAuth 用于本地 Node.js 脚本时,我遇到了一些奇怪的行为。我现在的目标是在用户授权我的项目时从用户那里获取刷新令牌。

我正在尝试尽可能多地依赖 Google 的库,但仍然遇到问题。

当我尝试运行设置时,我正确获取了 OAuth 页面并创建了一个授权令牌:

const { google } = require('googleapis');

const oauth2Client = new google.auth.OAuth2(
    clientId,
    clientSecret,
    'urn:ietf:wg:oauth:2.0:oob'
);
const scopes = [
    'https://www.googleapis.com/auth/calendar'
];

我在控制台中向用户提供 URL:

const url = oauth2Client.generateAuthUrl({
    // 'online' (default) or 'offline' (gets refresh_token)
    access_type: 'offline',

    // If you only need one scope you can pass it as a string
    scope: scopes
});

console.log(url);

然后我打开 URL 并生成令牌。我提示用户提供此值:

stdio.question('Authorization code', (err, code) => {
    // Use this code to obtain a refresh token
    console.log("CODE", code);
    oauth2Client.getToken(code, (err, tokens) => {
        console.log(err, tokens);
    });
});

当我到达这一点时,我遇到了一个错误:

error: 'invalid_grant', error_description: 'Bad Request'

目前还不清楚这是哪里出了问题。

如果我采用相同的身份验证令牌并使用 cURL,它实际上可以按预期工作,所以据我所知,这不是配置错误。

curl -s -X POST -d 'code='$CODE'&client_id='$CLIENT_ID'&client_secret='$CLIENT_SECRET'&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code' https://www.googleapis.com/oauth2/v4/token

{
  "access_token": "ACCESS",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "REFRESH"
}

更有趣的是,如果我运行流程并得到错误,尝试运行 cURL 命令将返回一个错误,表明请求在某种程度上被接受:

{
  "error": "invalid_grant",
  "error_description": "Code was already redeemed."
}

此 OAuth 库中发生了什么导致 cURL 未发生的无效授权问题,我可以做些什么来更正 Node.js 代码?

【问题讨论】:

    标签: oauth-2.0 google-oauth google-api-nodejs-client


    【解决方案1】:

    事实证明,stdio 库的一个问题是,您输入的所有文本在您获得回调之前最终都是 converted to lowercase。这就是导致invalid_grant 错误的原因。

    更好的方法是使用 Node.js 中内置的 readline 模块

    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    rl.question('Authorization code: ', (code) => {
      // Use this code to obtain a refresh token
      console.log("CODE", code);
      oauth2Client.getToken(code, (err, tokens) => {
        console.log(err, tokens);
        rl.close();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 2016-03-01
      • 2022-01-16
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多