มิดเดิลแวร์ยืนยันตัวตนด้วย JWT
สร้างการยืนยันตัวตนที่ปลอดภัยให้แอป Express ด้วยโทเค็นเว็บ JSON และเรียนรู้การปกป้องเส้นทางด้วยมิดเดิลแวร์ยืนยันตัวตนแบบกำหนดเอง
มิดเดิลแวร์ยืนยันตัวตนด้วย JWT เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “มิดเดิลแวร์ยืนยันตัวตนด้วย JWT”
สร้างการยืนยันตัวตนที่ปลอดภัยให้แอป Express ด้วยโทเค็นเว็บ JSON และเรียนรู้การปกป้องเส้นทางด้วยมิดเดิลแวร์ยืนยันตัวตนแบบกำหนดเอง คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “มิดเดิลแวร์ยืนยันตัวตนด้วย JWT” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การพัฒนามิดเดิลแวร์ Express แบบกำหนดเอง
- กลยุทธ์การจัดการข้อผิดพลาดทั่วทั้งระบบ
- การตรวจสอบอินพุตด้วย Joi/Express-Validator
- มิดเดิลแวร์ยืนยันตัวตนด้วย JWT