-
10. AuthMiddlewareMERN Stack ChatApp 2024. 8. 5. 15:52
https://www.youtube.com/watch?v=HArC6GxkMMI&list=PLKhlp2qtUcSZsGkxAdgnPcHioRr-4guZf&index=10
다음으로 서버에 인증 미들웨어를 만든다.
인증이 필요한 부분으로 이동할 때, 지금 만드는 미들웨어를 거친다음 원하는 곳으로 가게끔 할 수 있다.
지금만드는 건 인증이니깐 인증이 되야만 다음단계로 거치도록 할 수 있다.
미들웨어 안에서 req, res객체에 뭘 넣어줄수도 있고.
만들고 사용하는 방법은 먼저 미들웨어를 만들고
// backend/middleware/authMiddleward.js const jwt = require("jsonwebtoken"); const User = require("../models/userModel.js"); const asyncHandler = require("express-async-handler"); const protect = asyncHandler(async (req, res, next) => { console.log("protect "); }); module.exports = { protect };
라우터에서 행하고자 하는 곳에 끼워넣어주면 된다.
router.route("/").get(protect, allUsers)이런식으로. allUsers 메서드를 불러주기전에 protect를 불러줄 수 있다.
그럼 protect메서드를 만들어줘보자.
// backend/middleware/authMiddleward.js const jwt = require("jsonwebtoken"); const User = require("../models/userModel.js"); const asyncHandler = require("express-async-handler"); const protect = asyncHandler(async (req, res, next) => { console.log("protect "); let token; if ( req.headers.authorization && req.headers.authorization.startsWith("Bearer") ) { try { token = req.headers.authorization.split(" ")[1]; // decode token id const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded.id).select("-password"); next(); } catch (err) { res.status(401); throw new Error("Not authorized"); } } }); module.exports = { protect };
리퀘스트의 헤더에 authorization 토큰 (Bearer로 시작하는)을 검사하고, 디코드 해준다.
그리고 담겨있는 아이디의 정보를 password 만 빼고 select해준뒤, 리퀘스트 객체에 담고 next로 넘긴다.
이러면 protect 미들웨어 다음에 실행되는 메서드에서 req객체에 담긴 user정보를 쓸 수 있다.
(그런데 이렇게 하면 무슨 요청이 있을 때마다 유저정보를 가지러 db와 통신해야하는 게 너무 많다고 느껴질 수도 있다.
별로 보안이 필요하지 않은 유저정보일 경우에는 jwt를 만들 때, 그 안에 담아서 토큰을 만들어버리자.
그리고 decode해서 사용하자. 여기서는 서버와 통신해서 가져오는 걸로 하겠다.
보안이 필요한 유저정보의 경우 jwt에 담으면 안된다. payload는 쉽게 해독된다. 해독이라고 하기도 민망하고 https://jwt.io/ 이런데다가 토큰 복사붙여넣기 해보면 payload에 뭐 담겨있나가 다 보인다.
)
github : https://github.com/Wunhyeon/ChatApp-MERNStack/tree/10.authMiddleware
GitHub - Wunhyeon/ChatApp-MERNStack
Contribute to Wunhyeon/ChatApp-MERNStack development by creating an account on GitHub.
github.com
'MERN Stack ChatApp' 카테고리의 다른 글
12. 채팅방 프론트. 로그인보완 (서버사이트 상태저장) (0) 2024.08.06 11. 1:1 채팅방 API, 모든 내 대화방 가져오기, 그룹채팅방 만들기, 채팅방 이름 바꾸기 (0) 2024.08.05 9. Find Users API (0) 2024.08.05 8.Login (0) 2024.08.05 7. Front 회원가입 페이지 전면 수정 및 서버통신 (0) 2024.08.04