Node.js Web アプリケーションで Web API を呼び出す
適用対象: 従業員テナント 外部テナント (詳細情報)
この記事では、「アクセス トークンを取得する」で取得したアクセス トークンを使用して、Node.js クライアント Web アプリから Web API を呼び出す方法について説明します。 Web API は、Microsoft Entra 外部 ID によって保護されます。 この記事は、4 部構成のガイド シリーズの第 4 部であり、最後の部分です。
前提条件
- このガイド シリーズの最初のパートである「Node.js Web アプリケーションで API を呼び出すための外部テナントを準備する」の手順を完了します。
- このガイド シリーズの第 2 部「Node.js Web アプリケーションで API を呼び出すアプリを準備する」の手順を完了します。
- このガイド シリーズの第 3 部「Node.js Web アプリでアクセス トークンを取得する」の手順を完了します。
コードの更新
コード エディターで routes/todos.js ファイルを開き、次のコードを追加します。
const express = require('express'); const router = express.Router(); const toDoListController = require('../controller/todolistController'); const authProvider = require('../auth/AuthProvider'); const { protectedResources } = require('../authConfig'); // custom middleware to check auth state function isAuthenticated(req, res, next) { if (!req.session.isAuthenticated) { return res.redirect('/auth/signin'); // redirect to sign-in route } next(); } // isAuthenticated checks if user is authenticated router.get('/',isAuthenticated, authProvider.getToken(protectedResources.toDoListAPI.scopes.read),toDoListController.getToDos); router.delete('/', isAuthenticated,authProvider.getToken(protectedResources.toDoListAPI.scopes.write),toDoListController.deleteToDo); router.post('/',isAuthenticated,authProvider.getToken(protectedResources.toDoListAPI.scopes.write),toDoListController.postToDo); module.exports = router;
このファイルには、保護された API でリソースを作成、読み取り、削除するための高速ルートが含まれています。 各ルートでは、次の 3 つのミドルウェア関数が使用されます。これらは、そのシーケンスで実行されます。
isAuthenticated
は、ユーザーが認証されているかどうかを確認します。getToken
はアクセス トークンを要求します。 この関数は、以前に「アクセス トークンの取得」で定義しています。 たとえば、リソースの作成ルート (POST 要求) は、読み取りと書き込みのアクセス許可を持つアクセス トークンを要求します。最後に、
postToDo
またはdeleteToDo
getToDos
メソッドで、リソースを操作する実際のロジックを処理します。 これらの関数は、controller/todolistController.js ファイルで定義されます。
コード エディターで controller/todolistController.js ファイルを開き、次のコードを追加します。
const { callEndpointWithToken } = require('../fetch'); const { protectedResources } = require('../authConfig'); exports.getToDos = async (req, res, next) => { try { const todoResponse = await callEndpointWithToken( protectedResources.toDoListAPI.endpoint, req.session.accessToken, 'GET' ); res.render('todos', { isAuthenticated: req.session.isAuthenticated, todos: todoResponse.data }); } catch (error) { next(error); } }; exports.postToDo = async (req, res, next) => { try { if (!!req.body.description) { let todoItem = { description: req.body.description, }; await callEndpointWithToken( protectedResources.toDoListAPI.endpoint, req.session.accessToken, 'POST', todoItem ); res.redirect('todos'); } else { throw { error: 'empty request' }; } } catch (error) { next(error); } }; exports.deleteToDo = async (req, res, next) => { try { await callEndpointWithToken( protectedResources.toDoListAPI.endpoint, req.session.accessToken, 'DELETE', req.body._id ); res.redirect('todos'); } catch (error) { next(error); } };
これらの各関数は、API の呼び出しに必要なすべての情報を収集します。 その後、
callEndpointWithToken
関数に処理を委任し、応答を待機します。callEndpointWithToken
関数は fetch.js ファイルで定義されています。 たとえば、API でリソースを作成するために、postToDo
関数はエンドポイント、アクセス トークン、HTTP メソッド、および要求本文をcallEndpointWithToken
関数に渡し、応答を待機します。 次に、ユーザーを todo.hbs ビューにリダイレクトして、すべてのタスクを表示します。コード エディターで fetch.js ファイルを開き、次のコードを追加します。
const axios = require('axios'); /** * Makes an Authorization "Bearer" request with the given accessToken to the given endpoint. * @param endpoint * @param accessToken * @param method */ const callEndpointWithToken = async (endpoint, accessToken, method, data = null) => { const options = { headers: { Authorization: `Bearer ${accessToken}`, }, }; switch (method) { case 'GET': return await axios.get(endpoint, options); case 'POST': return await axios.post(endpoint, data, options); case 'DELETE': return await axios.delete(endpoint + `/${data}`, options); default: return null; } }; module.exports = { callEndpointWithToken, };
この関数は、実際の API 呼び出しを行います。 アクセス トークンをベアラー トークンの値として HTTP 要求ヘッダーに含める方法に注意してください。
//... headers: { Authorization: `Bearer ${accessToken}`, } //...
コード エディターで .env ファイルを開き、次の構成を追加します。
# Use this variable only in the development environment. # Please remove the variable when you move the app to the production environment. NODE_TLS_REJECT_UNAUTHORIZED='0'
.env ファイル内の
NODE_TLS_REJECT_UNAUTHORIZED='0'
設定は、Node.js に対して、自己署名証明書エラーなどの SSL 証明書エラーを無視するように指示します。コード エディターで、
app.js
ファイルを開き、次の操作を行います。次のコードを使用して、todo ルーターを追加します。
var todosRouter = require('./routes/todos');
次のコードを使用して、todo ルーターを使用します。
app.use('/todos', todosRouter);
Web アプリと API の実行とテスト
この時点で、クライアント Web アプリから Web API を呼び出す準備ができました。
ASP.NET Web API のセキュリティ保護に関する記事の手順を使用して、Web API アプリを起動します。 これで、Web API でクライアント要求を処理する準備が整いました。
ターミナルで、
ciam-sign-in-call-api-node-express-web-app
などのクライアント Web アプリを含むプロジェクト フォルダーに移動し、次のコマンドを実行します。npm start
クライアント Web アプリが起動します。
「サンプル Web アプリと API を実行してテストする」の手順を使用して、クライアント アプリが Web API を呼び出す方法を示します。
次のステップ
以下を行うことができます。