2024.01.12(금)
jwt.io에 다음과 같이 나와있다.
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:
Authorization: Bearer <token>
Authorization: <token>
형식으로 보냈지만 나는 위 형식을 따라 구현했다.jsonwebtoken 모듈에서는 다음 세 가지의 Error를 지원한다.
TokenExpiredError
: token이 만료되었을 때 error를 발생시킴JsonWebTokenError
: token이 유효하지 않을 때 error를 발생시킴NotBeforeError
: 현재 날짜가 nbf
claim보다 이전일때 error를 발생시킴jwt.verify(token, secretOrPublicKey)를 이용해 손쉽게 JWT을 검증할 수 있다.
다음과 같은 형식으로 검증 middleware를 만들었다.
req.decodedToken
에 decode한 JWT payload 객체를 담아 다음 middleware를 호출한다.const verifyToken = (req, res, next) => {
try {
// Authorization: Bearer <token>
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.PRIVATE_KEY, { ignoreExpiration: false });
req.decodedToken = decoded;
next();
} catch (error) {
next(error);
}
};
};
👉 https://github.com/do0ori/book-store-project/pull/9
모듈화하고 리팩토링하면 코드가 어느 정도 정리되는 것이 보여서 뿌듯하다.