AWS Lambda + Node.jsでMicrosoft Graphに対してPOSTして、oauth2のaccess_tokenを取得したいが404が返ってくる
解決したいこと
AWS Lambda + Node.jsでMicrosoft Graphに対してPOSTして、oauth2のaccess_tokenを取得したいです。
↓の実装の一環です。
現在、Node.jsのhttpsモジュールを使って、Microsoft Graphに対してシークレットなどをbodyに含めてPOSTし、oauth2のaccess_tokenを取得したいのですが、404が返ってきてしまいます。
Postmanでは成功する
Postmanで同じパラメーターでPOSTすると、200と望んだJSONが返ってきています。
コード
AWS Lambda + Node.jsです。
index.js
const AWS = require('aws-sdk');
exports.handler = async (event) => {
await getTasksNextDay()
};
async function getTasksNextDay() {
// tokenを生成
const url = `https://login.microsoftonline.com/${process.env["MS_TENANT"]}/oauth2/v2.0/token`
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
const data = {
client_id: process.env["MS_CLIENT_ID"],
scope: "https://graph.microsoft.com/.default",
client_secret: process.env["MS_CLIENT_SECRET"],
grant_type: "client_credentials",
};
const res = await sendHttpRequest(url, 'POST', headers, JSON.stringify(data));
console.log("res: ", res); // 空っぽ
}
// Httpリクエストを送信する。
async function sendHttpRequest(url, method, headers, bodyData) {
console.log('sendHttpRequest');
console.log('url:' + url);
console.log('method:' + method);
console.log('headers:' + JSON.stringify(headers));
console.log('body:' + bodyData);
// Node.jsのモジュール
const https = require('https');
const options = {
method: method,
headers: headers
};
// 非同期処理に成功した場合はresolveを、失敗した場合はrejectを呼ぶ
return new Promise((resolve, reject) => {
let req = https.request(url, options, (res) => {
console.log('responseStatusCode:' + res.statusCode); // 404
console.log('responseHeaders:' + JSON.stringify(res.headers)); // 上に示したheader
res.setEncoding('utf8');
let body = '';
res.on('data', (chunk) => {
body += chunk;
console.log('responseBody:' + chunk);
});
res.on('end', () => {
console.log('No more data in response.');
resolve(body);
});
}).on('error', (e) => {
console.log('problem with request:' + e.message);
reject(e);
});
req.write(bodyData);
req.end();
});
}
発生している問題・エラー
404が返ってきます。responseHeadersはこんな感じです。
responseHeaders
{
"set-cookie": [
"x-ms-gateway-slice=estsfd; path=/; secure; httponly"
],
"date": "Sat, 24 Sep 2022 05:05:12 GMT",
"connection": "close",
"content-length": "0"
}
よろしくお願いします。
1