다음을 통해 공유


Node.js 웹 애플리케이션에서 웹 API 호출

적용 대상: 회색 X 기호가 있는 흰색 원. 인력 테넌트 흰색 확인 표시 기호가 있는 녹색 원입니다. 외부 테넌트(자세히 알아보기)

이 문서에서는 액세스 토큰 획득에서 획득한 액세스 토큰을 사용해 자신의 Node.js 클라이언트 웹에서 웹 API를 호출하는 방법을 알아봅니다. 웹 API는 Microsoft Entra 외부 ID로 보호됩니다. 이 문서는 4부로 구성된 가이드 시리즈의 네 번째이며 마지막 부분입니다.

전제 조건

코드 업데이트

  1. 코드 편집기에서 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에서 리소스를 만들거나 읽고 삭제하기 위한 빠른 경로가 포함되어 있습니다. 각각의 경로는 해당 순서로 실행되는 세 가지 미들웨어 함수를 사용합니다.

    • isAuthenticated은(는) 사용자가 인증되었는지를 확인합니다.

    • getToken은 액세스 토큰을 요청합니다. 액세스 토큰 획득에서 이 함수를 미리 정의했습니다. 예를 들어 리소스 경로 만들기(POST 요청)는 읽기와 쓰기 권한이 있는 액세스 토큰을 요청합니다.

    • 마지막으로, postToDo 또는 deleteToDo getToDos 메서드는 리소스를 조작하기 위한 실제 논리를 처리합니다. 이들 함수는 controller/todolistController.js 파일에서 정의됩니다.

  2. 코드 편집기에서 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 보기에 리디렉션하여 모든 작업을 표시합니다.

  3. 코드 편집기에서 auth.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}`,
        }        
        //...
    
  4. 코드 편집기에서 .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' 설정은 자체 서명된 인증서 오류와 같은 SSL 인증서 오류를 무시하도록 Node.js에 지시합니다.

  5. 코드 편집기에서 app.js 파일을 연 다음, 다음을 수행합니다.

    1. 다음 코드를 사용하여 todo 라우터를 추가합니다.

          var todosRouter = require('./routes/todos');
      
    2. 다음 코드를 사용하여 todo 라우터를 사용합니다.

          app.use('/todos', todosRouter); 
      

웹앱 및 API 실행 및 테스트

이제 클라이언트 웹앱에서 웹 API를 호출할 준비가 된 것입니다.

  1. ASP.NET 웹 API 보안 문서의 단계를 따라 웹 API 앱을 시작하세요. 이제 웹 API가 클라이언트 요청을 처리할 준비가 되었습니다.

  2. 터미널에서 ciam-sign-in-call-api-node-express-web-app과 같은 클라이언트 웹앱이 포함된 프로젝트 폴더에 있는지 확인한 다음, 다음 명령을 실행합니다.

    npm start
    

    클라이언트 웹앱이 시작됩니다.

  3. 샘플 웹앱 및 API 실행 및 테스트에 나온 단계를 사용하여 클라이언트 앱이 웹 API를 호출하는 방법을 보여 줍니다.

다음 단계

다음을 수행하려고 할 수 있습니다.