我正在尝试使用 NodeJs 中的硬编码方法获取 OAuth 令牌。我已按照以下文章的说明从
https://developers.google.com/oauthplayground/
检索了 AUTHORIZATION_CODE:https://medium.com/@nickroach_50526/sending-emails-with-node-js-using-smtp-gmail-and-oauth2 -316fe9c790a1.
当我尝试根据访问令牌和刷新令牌交换授权代码时,OAuth 的 Playground 到目前为止会返回 HTTP 500。因此,我尝试了另一种方法,包括创建一个用于记录我的令牌的程序。因此我可以在其他应用程序中使用它们。
这是我的片段:
const {google} = require('googleapis');
const app= require("express")();
const oauth2Client = new google.auth.OAuth2(
"CLIENT_ID",
"CLIENT_SECRET",
"REDIRECT_URI"
);
app.get("/getToken", async (req,res)=>{
const tokens = await oauth2Client.getToken(
"AUTHORIZATION_CODE"
)
console.log("tokens: ", tokens)
oauth2Client.setCredentials(tokens);
res.send(tokens, oauth2Client)
})
当我启动程序时,我的控制台返回:“ UnhandledPromiseRejectionWarning:错误:redirect_uri_mismatch 在 Gaxios._request”。
我不明白为什么,因为我的重定向 UI 已有效地输入到我的
https://console.developers.google.com/apis/credentials/oauthclient/Id.com?project=Project_Name
页面中。
以硬编码方式检索令牌时我缺少什么?
我在这里面临同样的问题。通过反复试验,我发现如果您使用此方法生成它,则需要提供与
generateAuthUrl()
方法相同的 uri。
let { tokens } = await oauth2Client.getToken({
code,
redirect_uri: "http://localhost:3000/oauth2callback",
});