본문 바로가기
STUDY/Project

사용자 검증 미들웨어 기능 구현 - authMiddleware

by Y.Choi 2025. 5. 1.
728x90
반응형

 

사용자의 인증 상태를 검사하고 인증된 경우 req.user에 사용자 정보를 저장한다.

 

게시글 작성, 댓글 작성, 프로필 수정, 비공개 페이지 접근 등 로그인한 사용자만 이용 가능한 API에서 사용할 수 있다.

클라이언트에서 로그인을 했어도 실제로는 서버에서 검증할 방법이 필요하다.

토큰이 유효하면 컨트롤러에서 req.user로 사용자 정보 활용이 가능하도록 한다.

 

 

backend/middleware/authMiddleware.js

const jwt = require('jsonwebtoken');
const User = require('../models/User');

const protect = async (req, res, next) => {
  let token;

  // 토큰이 헤더에 있는지 확인 (Bearer 토큰 방식)
  if (req.headers.authorization?.startsWith('Bearer')) {
    try {
      // 헤더: "Bearer asdf1234..." → "asdf1234..."만 추출
      token = req.headers.authorization.split(' ')[1];

      // 토큰 검증 및 복호화
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      // 복호화된 payload에서 id 추출 후 DB에서 사용자 조회
      req.user = await User.findById(decoded.id).select('-password');

      next(); // 다음 미들웨어 또는 라우터로 진행
    } catch (error) {
      // 토큰이 만료되었거나 조작된 경우 등 에러
      res.status(401).json({
        message: '토큰 인증 실패',
        error: error.message
      });
    }
  } else {
    // Authorization 헤더가 없거나 형식이 잘못된 경우
    res.status(401).json({ message: '토큰이 없습니다' });
  }
};

module.exports = protect;

 

 

/ if(req.headers.authorization?.startsWith('Bearer')) : HTTP 요청 헤더에 인증 토큰이 있는지 확인한다.

- req.headers.authorization : 브라우저나 Postman, Thunder Client에서 보낸 헤더 중 Authorization 값

- 보통 로그인된 사용자일 경우 "Bearer <token>" 형태로 들어옴

- startsWith('Bearer') : 이 형식이 맞는지 검사해서 맞을 때만 토큰을 추출하여 검증을 시도한다.

( req.headers.authorization === "Bearer eyJhbGciOi..." )

- ?. (Optional Chaining)은 authorization이 undefined일 때 에러가 나지 않도록 해준다.

 

 

 

 

 

| 응용하기 (재사용) 예시

 

/ 게시글 작성 / router.post('/posts', protect, postController.createPost)

/ 댓글 등록 / router.post('/comments', protect, commentController.create)

/ 프로필 수정 / router.put('/user/profile', protect, userController.update)

/ 비공개 글 목록 / router.get('/my/posts', protect, postController.myPosts)

 

라우터에서 protect 미들웨어만 추가하면 자동으로 인증된 사용자만 접근이 가능하게 한다.

728x90
반응형