GoogleApis:无法使用服务帐户json文件进行身份验证



我正在尝试验证Node.js应用程序(它最终将成为Express.js后端的一部分(的gmailapi。在我的.env文件中,我在env变量GOOGLE_APPLICATION_CREDENTIALS下设置了credentials.json文件的绝对路径。

然后我尝试运行一个简单的功能来打印消息列表

async function runSample() {
<message setup removed>
try {
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
},
});
console.log(res.data);
return res.data;
} catch (error) {
throw new Error(error);
}
}
runSample();
// (node:15522) UnhandledPromiseRejectionWarning:
// Error: Error: Login Required.

我认为这个身份验证流不需要显式的范围授予或登录。如果这是不正确的,需要做哪些更改来处理登录?

根据官方文档,您需要通过oAuth2进行授权,还需要指定范围

const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
const TOKEN_PATH = 'token.json';

fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), runSample);  // this is important
});
/**
* 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 getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}

async function runSample(auth) {

const gmail = google.gmail({version: 'v1', auth});

try {
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
},
});
console.log(res.data);
return res.data;
} catch (error) {
throw new Error(error);
}
}

最新更新