我一直在使用 k6 来加载测试 Web 应用程序,我需要访问 gmail 收件箱进行解析。由于 k6 不支持 googleapis 和 axios,我使用 k6/http 模块创建了 http 请求。我能够检索访问令牌,但无法访问邮件收件箱。遇到这个错误
INFO[0001] {"error":{"code":401,"message":"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","errors":\[{"message":"Login Required.","domain":"global","reason":"required","location":"Authorization","locationType":"header"}],"status":"UNAUTHENTICATED","details":[{"domain":"googleapis.com","metadata":{"service":"gmail.googleapis.com","method":"caribou.api.proto.MailboxService.ListMessages"},"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"CREDENTIALS_MISSING"}]}}
这是手动编写的访问令牌检索部分
const payload = `client_id=${clientId}&client_secret=${clientSecret}&refresh_token=${refreshToken}&grant_type=refresh_token`;
const tokenResponse = http.post(tokenUrl, payload, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
const accessToken = tokenResponse.json().access_token;
它在控制台中记录了 accesstoken
const options = {
url: 'https://gmail.googleapis.com/gmail/v1/users/[email protected]/messages',
params: {
q: `from:[email protected] to:${profilesEmailAddress}`,
},
headers: {
Authorization: `Bearer ${accessToken.access_token}`,
},
};
const response = http.get(options.url, options.params, options.headers);
这用于访问 gmail 收件箱,我使用 http.get() 而不是 axios()。它无法访问邮件收件箱并返回上述错误。有人可以帮我弄这个吗?我究竟做错了什么?为什么无法访问邮件正文?我能够使用相同的逻辑 cURL 命令在 Postman 中获得响应。
curl -X GET \
'https://gmail.googleapis.com/gmail/v1/users/[email protected]/messages?q=from%3Ano-reply%40rework.link%20to%[email protected]' \
-H 'Authorization: Bearer <access_token>'
谢谢。
您似乎错误地访问了访问令牌,您尝试访问字符串的属性(
accessToken.access_token
)。您可以记录 options.headers.Authorization
的值吗?它是否符合您的预期值?
此外,您没有正确传递标头,它们必须作为选项参数的属性传递(
{ headers: { … } }
),但是您传递的选项参数没有标头键,而是将标头本身作为选项传递({ … }
) .
以下固定和简化的代码应该可以工作:
const payload = `client_id=${clientId}&client_secret=${clientSecret}&refresh_token=${refreshToken}&grant_type=refresh_token`;
const tokenResponse = http.post(tokenUrl, {
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token',
});
const accessToken = tokenResponse.json('access_token');
const response = http.get(
'https://gmail.googleapis.com/gmail/v1/users/[email protected]/messages',
{ q: `from:[email protected] to:${profilesEmailAddress}` },
{
headers: {
authorization: `bearer ${accessToken}`,
}
});