보호된 경로 및 미들웨어
JWT를 검증하고 인증된 사용자로 접근을 제한하는 미들웨어를 구현하여 API 엔드포인트를 보호하는 방법을 학습합니다.
보호된 경로 및 미들웨어은(는) CoddyKit의 무료 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Powered SaaS: Stripe + Auth + Billing + Deploy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Securing Your Digital Doors
Imagine a VIP lounge. Not everyone can just walk in, right? Some areas of your application, like a user's profile or settings, are just like that VIP lounge. They contain sensitive data or allow critical actions.
These are called protected routes. They ensure that only authenticated and authorized users can access specific resources or perform certain operations. Without them, anyone could potentially view or alter sensitive user data.
Your API's Security Guard: Middleware
How do we protect these routes? That's where middleware comes in!
Middleware functions are like security guards that stand between a client's request and your server's route handler. They can inspect, modify, or even terminate requests before they reach their final destination.
Think of it as a checkpoint. Every request must pass through, and the middleware decides if it's allowed to proceed.
The Middleware Flow
Middleware fits right into the request-response cycle. When a request hits your server, it first goes through any configured middleware functions, one by one.
- Intercept: Middleware intercepts the incoming request.
- Process: It performs its logic (e.g., logging, authentication, data parsing).
- Pass On: If all checks pass, it uses a special function (often called
next()) to pass control to the next middleware or the final route handler. - Block: If a check fails (e.g., unauthorized), it can send a response directly and stop the request from going further.
First Middleware Steps
Let's see a basic example. Here's a simple Node.js Express middleware that logs requests. Notice the next() function – it's crucial for passing control.
Try running this example and see the console output!
const express = require('express');
const app = express();
// Define our simple logging middleware
function requestLogger(req, res, next) {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Crucial: pass control to the next handler
}
// Apply the middleware to all incoming requests
app.use(requestLogger);
// Define a simple route
app.get('/', (req, res) => {
res.send('Hello from the server!');
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));Locating the Authentication Token
For authentication, our middleware needs to find the JSON Web Token (JWT) sent by the client. JWTs are typically sent in the Authorization header of an HTTP request, using the Bearer scheme.
It looks like this: Authorization: Bearer YOUR_JWT_TOKEN_HERE
Our middleware's first job is to extract this token from the request headers.
Checking the Token's Authenticity
Once we have the token, we need to verify it. This involves checking its signature using the secret key that was used to sign it. If the token's signature is valid, we know it hasn't been tampered with.
Here's how you might verify a token using a common library (like jsonwebtoken in Node.js). For this example, we'll simulate a valid token.
const jwt = require('jsonwebtoken'); // npm install jsonwebtoken
const SECRET_KEY = 'my_super_secret_key'; // Keep this secure in real apps!
const mockPayload = { id: 'user123', username: 'alice' };
// 1. Create a mock token (what a login endpoint would generate)
const mockToken = jwt.sign(mockPayload, SECRET_KEY, { expiresIn: '1h' });
console.log('Generated Token:', mockToken);
// 2. Verify the token in our middleware
jwt.verify(mockToken, SECRET_KEY, (err, user) => {
if (err) {
console.log('Token verification failed:', err.message);
} else {
console.log('Token is valid! User:', user);
// In a real middleware, you'd attach 'user' to req object
}
});
Denying Access
What if the token is missing or invalid? Our middleware must respond with an error and prevent the request from reaching the protected route.
- Missing Token: If no
Authorizationheader or token is found, return a401 Unauthorizedstatus. - Invalid Token: If the token exists but is malformed, expired, or has an invalid signature, return a
403 Forbiddenstatus.
This is crucial for security!
Making User Info Available
If the JWT is successfully verified, it contains a payload with user information (like user ID, username, etc.). Our middleware can extract this data and attach it to the request object.
This means that any subsequent route handler for a protected route will have direct access to the authenticated user's details without needing to re-parse the token.
Example: req.user = decodedPayload;
Full Authentication Middleware
Here's a complete Node.js Express setup with our authentication middleware. Notice how authenticateToken is applied to the /profile route, making it protected.
Run this. Try accessing /profile without a token, then with a valid token (from Scene 6).
const express = require('express');
const jwt = require('jsonwebtoken'); // npm install jsonwebtoken
const app = express();
const SECRET_KEY = 'my_super_secret_key'; // Use env vars in production!
// Middleware to authenticate JWT
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (token == null) {
return res.status(401).send('Access Denied: No token provided');
}
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) {
return res.status(403).send('Access Denied: Invalid token');
}
req.user = user; // Attach user payload to request
next(); // Pass to the next handler/route
});
}
// An unprotected public route
app.get('/public', (req, res) => {
res.send('This is a public route. No authentication needed.');
});
// A protected route
app.get('/profile', authenticateToken, (req, res) => {
res.json({
message: `Welcome to your profile, ${req.user.username}!`,
userId: req.user.id
});
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));Middleware Checkpoint
Consider an authentication middleware designed to protect a route. What is the primary purpose of calling next() within the middleware function?
Lesson Summary: Secure Routes
Great job! In this lesson, you've learned to secure your API endpoints with protected routes.
- We explored how middleware acts as an intermediary, inspecting requests before they reach sensitive parts of your application.
- You saw how to implement an authentication middleware to extract and validate JWTs from incoming requests.
- We covered handling missing or invalid tokens by sending appropriate error responses (
401,403). - Finally, you learned how to attach authenticated user data to the request object and apply this middleware to specific routes, ensuring only authorized users can access them.
Your API is now much more secure!
AI 튜터와 함께 AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“보호된 경로 및 미들웨어” 강의는 무료인가요?
네 — “보호된 경로 및 미들웨어” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의 전체를 잠금 해제할 수 있습니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
“보호된 경로 및 미들웨어”에서 뭘 배우나요?
JWT를 검증하고 인증된 사용자로 접근을 제한하는 미들웨어를 구현하여 API 엔드포인트를 보호하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Powered SaaS: Stripe + Auth + Billing + Deploy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“보호된 경로 및 미들웨어” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 사용자 등록 및 해싱
- 로그인 및 JWT 생성
- 보호된 경로 및 미들웨어
- 비밀번호 재설정과 이메일 인증