Node.js · 2026-01-18

Node.js로 Authorization Code OAuth2 서버 구현

Node.js로 Authorization Code 흐름을 따라 OAuth2 서버 구현 과정을 단계별로 설명한다. 예제 코드, 테스트 방법, 저장소 설계와 보안 고려사항을 포함한 초보 개발자 대상 튜토리얼

작성일 : 2026-01-18 ㆍ 작성자 : 관리자
post
목차

개요

이 글에서는 Node.js 환경에서 Authorization Code 흐름을 사용하는 OAuth2 서버 구현을 차근차근 설명한다. 처음 접하는 개발자도 이해하기 쉽게 개념, 엔드포인트 설계, 간단한 코드 예제, 테스트 방법까지 포함한다. 핵심은 인증 코드 발급과 교환 과정이며, 실습용으로 메모리 저장소를 사용한다.

Authorization Code 흐름 이해

흐름 요약

  • 사용자가 클라이언트(앱)에서 인증 요청을 실행한다.
  • 인증 서버는 사용자 인증 후 authorization code를 발급하고 리다이렉트한다.
  • 클라이언트는 authorization code를 받아 토큰 엔드포인트에 교환 요청을 보낸다.
  • 인증 서버는 code를 검증한 뒤 access token(및 refresh token)을 발급한다.

이 방식은 서버 사이드 애플리케이션에 적합하며, 클라이언트 시크릿을 안전하게 보관할 수 있을 때 권장된다.

환경 및 패키지

간단한 구현을 위해 express와 body-parser, crypto를 사용한다. 실제 운영에서는 데이터베이스와 HTTPS가 필수다.

npm init -y
npm install express body-parser

간단한 서버 구현

아래 코드는 메모리 기반의 최소 구현 예제다. 실제 서비스용이 아니며 학습 목적에 맞춘 구조다.

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 메모리 저장소 (예제용)
const clients = {
  'client_1': { clientId: 'client_1', redirectUris: ['http://localhost:9000/callback'], clientSecret: 'secret' }
};
const authCodes = {}; // code: { clientId, redirectUri, user }
const tokens = {}; // accessToken: { clientId, user }

function generateCode() { return crypto.randomBytes(16).toString('hex'); }
function generateToken() { return crypto.randomBytes(32).toString('hex'); }

// /authorize 엔드포인트: 사용자 인증 후 코드 발급
app.get('/authorize', (req, res) => {
  const { response_type, client_id, redirect_uri, state } = req.query;
  const client = clients[client_id];
  if (!client || !client.redirectUris.includes(redirect_uri)) {
    return res.status(400).send('Invalid client or redirect URI');
  }
  if (response_type !== 'code') return res.status(400).send('Unsupported response_type');

  // 실제로는 사용자 인증과 동의 화면 필요
  const user = { id: 'user123' };
  const code = generateCode();
  authCodes[code] = { clientId: client_id, redirectUri: redirect_uri, user };

  const redirect = `${redirect_uri}?code=${code}${state ? '&state=' + state : ''}`;
  res.redirect(redirect);
});

// /token 엔드포인트: code 교환으로 토큰 발급
app.post('/token', (req, res) => {
  const { grant_type, code, redirect_uri, client_id, client_secret } = req.body;
  if (grant_type !== 'authorization_code') return res.status(400).json({ error: 'unsupported_grant_type' });

  const client = clients[client_id];
  if (!client || client.clientSecret !== client_secret) return res.status(401).json({ error: 'invalid_client' });

  const saved = authCodes[code];
  if (!saved || saved.clientId !== client_id || saved.redirectUri !== redirect_uri) {
    return res.status(400).json({ error: 'invalid_grant' });
  }

  // 발급
  const accessToken = generateToken();
  tokens[accessToken] = { clientId: client_id, user: saved.user };
  delete authCodes[code]; // one-time use

  res.json({ access_token: accessToken, token_type: 'Bearer', expires_in: 3600 });
});

app.listen(8000, () => console.log('Auth server started on 8000'));

테스트 방법

브라우저에서 /authorize 엔드포인트에 접근해 authorization code를 확인한 뒤, token 교환을 curl로 실행한다.

# 1) 브라우저로 접속
# http://localhost:8000/authorize?response_type=code&client_id=client_1&redirect_uri=http://localhost:9000/callback&state=xyz

# 2) 받은 code로 토큰 요청
curl -X POST http://localhost:8000/token \
  -H 'Content-Type: application/json' \
  -d '{"grant_type":"authorization_code","code":"받은_code","redirect_uri":"http://localhost:9000/callback","client_id":"client_1","client_secret":"secret"}'

설계 및 보안 고려사항

  • 실제 서비스에서는 HTTPS를 강제한다.
  • 클라이언트 시크릿은 안전한 저장소에 보관한다.
  • authorization code와 access token은 만료 시간과 리프레시 토큰 정책을 적용한다.
  • CSRF 공격 방지를 위해 state 파라미터를 검증한다.
  • 토큰 저장은 데이터베이스와 캐시를 이용해 확장성을 고려한다.

정리

이 글에서는 Node.js 환경에서 Authorization Code 흐름을 직접 구현하는 방법을 다뤘다. 핵심은 /authorize에서 code를 발급하고, /token에서 코드 검증 후 토큰을 발급하는 과정이다. 제시한 예제는 학습용이므로, 실제 서비스 적용 시 HTTPS, DB 저장, 시크릿 관리, 로그와 모니터링 같은 추가 작업이 필요하다. OAuth2 Node 튜토리얼로서 기본 개념과 구현 흐름을 이해하는 데 도움이 되길 바란다.

Node.js OAuth2 서버 구현 Authorization Code 예제 Node OAuth2 Node 튜토리얼 OAuth2 Authorization Code 인증 서버 Node.js 토큰 발급