kakudaisuke
@kakudaisuke (daisuke kaku)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

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が返ってきています。

スクリーンショット 2022-09-24 14.09.51.png

コード

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"
}

よろしくお願いします。

0

1Answer

ここが原因かはわかりませんが、とりあえずリクエストヘッダーのContent-Typeはjsonだと思います

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',
+    'Content-Type': 'application/json',    
  };
  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); // 空っぽ
}

また、process.env["MS_TENANT"]は正しくセットされていますか?
(= sendHttpRequest内の url のログは意図したURLが表示されていますか?

0Like

Your answer might help someone💌