JWT를 사용한 인증 미들웨어
JSON 웹 토큰으로 Express 앱에 안전한 인증을 구축하고, 사용자 지정 인증 미들웨어로 라우트를 보호하는 방법을 배웁니다.
JWT를 사용한 인증 미들웨어은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Tokens?
HTTP is stateless: the server forgets you between requests. To know who is making a request, the client sends proof of identity each time.
JSON Web Tokens (JWT) are a popular, stateless way to carry that proof without storing sessions on the server.
Anatomy of a JWT
A JWT is three Base64 sections separated by dots:
- Header: the signing algorithm
- Payload: claims like user id and role
- Signature: verifies the token was not tampered with
The payload is encoded, not encrypted — never put secrets in it.
// xxxxx.yyyyy.zzzzz
// header.payload.signatureInstalling jsonwebtoken
The jsonwebtoken package handles creating and verifying tokens.
// npm install jsonwebtoken
const jwt = require('jsonwebtoken');Signing a Token on Login
After verifying a user's credentials, call jwt.sign() with the payload, a secret, and options like expiry. Send the resulting token back to the client.
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });Sending the Token
The client stores the token and sends it back on each request, usually in the Authorization header using the Bearer scheme.
// Authorization: Bearer eyJhbGci...Reading the Token in Middleware
Auth middleware extracts the token from the header. Split off the Bearer prefix to get the raw token string.
function auth(req, res, next) {
const header = req.get('Authorization') || '';
const token = header.split(' ')[1];
// verify next...
}Verifying the Token
jwt.verify() checks the signature and expiry. If valid it returns the decoded payload; if not it throws, so wrap it in try/catch.
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}Complete Auth Middleware
Putting it together, this middleware rejects missing or invalid tokens and attaches the user to the request for downstream handlers.
function auth(req, res, next) {
const token = (req.get('Authorization') || '').split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}Protecting Routes
Apply the middleware to any route that requires login. Express runs it before the handler, blocking unauthenticated requests automatically.
app.get('/profile', auth, (req, res) => {
res.json({ id: req.user.userId });
});Role-Based Authorization
Authentication answers "who are you?"; authorization answers "are you allowed?". A second middleware can check req.user.role set by the auth step.
function requireAdmin(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
next();
}
app.delete('/users/:id', auth, requireAdmin, handler);Security Best Practices
Keep tokens safe:
- Store the secret in an environment variable, never in code
- Use short expiry times and refresh tokens for longer sessions
- Always serve over HTTPS
- Return
401for missing/invalid auth,403for insufficient permissions
Quick Check
Test your understanding of JWT auth.
Recap
You built stateless authentication with JWT:
- Sign a token on login with
jwt.sign() - Send it via the
Authorization: Bearerheader - Verify it in custom middleware with
jwt.verify() - Attach
req.userand protect routes - Add role checks for authorization
This is the foundation of secure Express APIs.
자주 묻는 질문
“JWT를 사용한 인증 미들웨어” 강의는 무료인가요?
네 — “JWT를 사용한 인증 미들웨어” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“JWT를 사용한 인증 미들웨어”에서 뭘 배우나요?
JSON 웹 토큰으로 Express 앱에 안전한 인증을 구축하고, 사용자 지정 인증 미들웨어로 라우트를 보호하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“JWT를 사용한 인증 미들웨어” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 사용자 정의 Express 미들웨어 개발
- 전역 오류 처리 전략
- Joi/Express-Validator로 입력값 검증
- JWT를 사용한 인증 미들웨어