JWT와 쿠키 사용해보기

하정현·2023년 11월 16일

Node.js

목록 보기
11/12

오늘 한일
회원가입후 로그인 인증하는 기능을 만들었다.
https://gabojok.tistory.com/213 <- 이분 블로그를 보고 따라햇다.

router.post("/login", async (req, res) => {
  const { userId, password } = req.body;

  const user = await User.findOne({ userId });

  if (!user || password !== user.password) {
    res.status(400).json({
      errorMessage:
        "사용자가 존재하지 않거나, 사용자의 password와 입력받은 password가 일치하지 않습니다.",
    });
    return;
  }

  const token = jwt.sign({ userId: user.userId }, "sparta-secret-key", {
    expiresIn: "12h",
  });

  res.cookie("authorization", `Bearer ${token}`);
  return res.status(201).end();
});

router.get("/login", authMiddleWare, async (req, res) => {
  res.json({ message: "로그인 성공" });
});

module.exports = router;

jwt를 사용 하는 방법이다.
터미널에서 npm install jsonwebtoken 해주고

쿠키에 담아서 보내준다.
Bearer authentication은 아직 잘 모르겠다.

/router

const jwt = require("jsonwebtoken");

  const token = jwt.sign({ userId: user.userId }, "sparta-secret-key", {
    expiresIn: "12h",
  });

res.cookie("authorization", `Bearer ${token}`);

/middleware

const db = require("../models");
const User = db.User;

module.exports = async (req, res, next) => {
  const { authorization } = req.cookies;
  const [authType, authToken] = authorization.split(" ");

  if (authType !== "Bearer" || !authToken) {
    res.status(400).json({
      errorMessage: "로그인 후 사용이 가능한 API 입니다.",
    });
    return;
  }

  try {
    const authorization = jwt.verify(authToken, "sparta-secret-key");
    console.log(authorization);

    if (!authorization) {
      return res.status(401).json({ message: "로그인 필요" });
    }

    const findUser = await User.findOne({
      where: { userId: authorization.userId },
    });

    if (!findUser) {
      return res.status(401).json({ message: "로그인 해" });
    }

    res.locals.user = findUser;
  } catch (error) {
    console.log(error);
    return res.status(401).json({ message: "로그인 해줘" });
  }

  next();
};

미들웨어까지 구현
사실 위에 블로그 코드랑 별로 다를게 없긴한데
res.locals.user에서
locals -> s를 빼먹어서 애먹었다.
안되는 부분들은 하나하나 console.log를 찍어가며 찾아가니까 좋았다.
이제는 시간이 걸리더라도 문제를 해결하는 빈도수가 늘어나는 것 같아 기쁘다!

0개의 댓글