
DeepSeek R1 × 飛書多維表格賦能教育領域
為了實現這一目標,我們將使用以下技術棧:
首先,創建一個項目文件夾并初始化npm項目。在終端中運行以下命令:
mkdir node-auth-api
cd node-auth-api
npm init -y
安裝必要的依賴:
npm install express jsonwebtoken
npm install -g nodemon
創建app.js
文件,并編寫基本的Express API代碼:
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.get('/api', (req, res) => {
res.json({ message: 'Welcome to the API' });
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
運行以下命令啟動服務器:
nodemon app.js
使用Postman測試API:
GET http://localhost:5000/api
接下來,創建一個受保護的POST路由:
app.post('/api/posts', (req, res) => {
res.json({ message: 'Post created' });
});
測試此路由:
POST http://localhost:5000/api/posts
創建一個登錄路由,用于生成和返回JWT:
app.post('/api/login', (req, res) => {
// 在實際應用中,這里應該驗證用戶憑據
const user = {
id: 1,
username: 'Brad',
email: 'brad@gmail.com'
};
jwt.sign({ user }, 'your_jwt_secret', { expiresIn: '30s' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
});
測試登錄路由:
POST http://localhost:5000/api/login
實現一個中間件函數,用于驗證請求中的JWT:
function verifyToken(req, res, next) {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
jwt.verify(req.token, 'your_jwt_secret', (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
next();
}
});
} else {
res.sendStatus(403);
}
}
將中間件應用于受保護路由:
app.post('/api/posts', verifyToken, (req, res) => {
res.json({ message: 'Post created', authData: req.authData });
});
在Postman中測試受保護路由。在請求頭中包含JWT:
Authorization: Bearer <your_jwt_token>
POST http://localhost:5000/api/posts
在登錄路由中設置JWT過期時間:
jwt.sign({ user }, 'your_jwt_secret', { expiresIn: '30s' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
測試過期的JWT:
POST http://localhost:5000/api/posts
通過本教程,我們學習了如何使用JWT保護API路由。從項目搭建到令牌驗證,我們全面掌握了API認證的核心技能。希望這些內容對你有所幫助!
原文引自YouTube視頻:https://www.youtube.com/watch?v=7nafaH9SddU