node.js - 不从授权代码返回刷新 token

标签 node.js oauth google-authentication google-apis-explorer refresh-token

我正在使用 Node 中的 googleapis 包从前端传递的授权代码中获取刷新 token 和访问 token ,但每次我都会收到以下错误。

  {      
      error: 'redirect_uri_mismatch',
      error_description: 'Bad Request' 
  }

我知道当我们不匹配在控制台中作为回调 URL 传递的 URL 时会出现此错误。 https://console.cloud.google.com/apis/credentials

但我已经在控制台中设置了正确的 URL。仍然不确定代码有什么问题。

使用 /auth 将 token 从 front-end 传递到 node-server

const {
    google
} = require("googleapis");
const OAuth2 = google.auth.OAuth2;
var bodyParser = require('body-parser')

const express = require('express');
const app = express();
app.use(bodyParser.json());

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});


app.use('/tokenCallback', (req, res) => {
    console.log(req);
    res.send('An alligator approaches!');
});

app.post('/auth', (req, res) => {
    runProcess(req.body.auth);
    res.send('An alligator approaches!');
});

app.listen(4300);

function runProcess(code) {

    const oauth2client = new OAuth2(
        "210347756664-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
        "57ZU6JuQ7oQ7SvSFtki5atxx", // Client Secret
        "http://localhost:4300/tokenCallback",
    );

    oauth2client.getToken(code, (e) => {
        console.log(e);
    });

    oauth2client.on('tokens', (tokens) => {
        if (tokens.refresh_token) {
            console.log("refresh token", tokens);
        }
    });

}

我们将不胜感激任何人的帮助。

最佳答案

redirect_uri_mismatch 表示您的应用未发送有效的重定向 URI,或者未在 Google Cloud Console 上注册。

确保在 Console -> APIs & Services -> Credentials -> OAuth client IDs -> (your key) 中添加了 http://localhost:4300/tokenCallback URI。

关于node.js - 不从授权代码返回刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727646/

相关文章:

.net - 尝试对 Twitter 进行 OAuth 并返回到 http ://Localhost:port

python - Mendeley Python SDK 中的身份验证问题

javascript - 从 google Drive 自行下载 xlsx 文件

node.js - 仅将 JsonSchema 与 Mongoose 一起使用可能吗?

python - 使用 Google API 获取用户电子邮件的最佳方式是什么?

reactjs - 无法解决reactjs中google身份验证中的firebase/app错误

authentication - 如何在azure移动服务中链接不同的身份验证提供商

google-authentication - 将 Google Web Auth 添加到 Svelte/Sapper 的 "right"方法是什么?

javascript - Passport-Google-OAuth 回调不起作用

javascript - 我的 Jade 怎么了?