
一步步教你進(jìn)行 Python REST API 身份驗(yàn)證
為了實(shí)現(xiàn)這一目標(biāo),我們將使用以下技術(shù)棧:
首先,創(chuàng)建一個(gè)項(xiàng)目文件夾并初始化npm項(xiàng)目。在終端中運(yùn)行以下命令:
mkdir node-auth-api
cd node-auth-api
npm init -y
安裝必要的依賴(lài):
npm install express jsonwebtoken
npm install -g nodemon
創(chuàng)建app.js
文件,并編寫(xiě)基本的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}
);
});
運(yùn)行以下命令啟動(dòng)服務(wù)器:
nodemon app.js
使用Postman測(cè)試API:
GET http://localhost:5000/api
接下來(lái),創(chuàng)建一個(gè)受保護(hù)的POST路由:
app.post('/api/posts', (req, res) => {
res.json({ message: 'Post created' });
});
測(cè)試此路由:
POST http://localhost:5000/api/posts
創(chuàng)建一個(gè)登錄路由,用于生成和返回JWT:
app.post('/api/login', (req, res) => {
// 在實(shí)際應(yīng)用中,這里應(yīng)該驗(yàn)證用戶(hù)憑據(jù)
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 });
});
});
測(cè)試登錄路由:
POST http://localhost:5000/api/login
實(shí)現(xiàn)一個(gè)中間件函數(shù),用于驗(yàn)證請(qǐng)求中的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);
}
}
將中間件應(yīng)用于受保護(hù)路由:
app.post('/api/posts', verifyToken, (req, res) => {
res.json({ message: 'Post created', authData: req.authData });
});
在Postman中測(cè)試受保護(hù)路由。在請(qǐng)求頭中包含JWT:
Authorization: Bearer <your_jwt_token>
POST http://localhost:5000/api/posts
在登錄路由中設(shè)置JWT過(guò)期時(shí)間:
jwt.sign({ user }, 'your_jwt_secret', { expiresIn: '30s' }, (err, token) => {
if (err) throw err;
res.json({ token });
});
測(cè)試過(guò)期的JWT:
POST http://localhost:5000/api/posts
通過(guò)本教程,我們學(xué)習(xí)了如何使用JWT保護(hù)API路由。從項(xiàng)目搭建到令牌驗(yàn)證,我們?nèi)嬲莆樟薃PI認(rèn)證的核心技能。希望這些內(nèi)容對(duì)你有所幫助!
原文引自YouTube視頻:https://www.youtube.com/watch?v=7nafaH9SddU
對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力
一鍵對(duì)比試用API 限時(shí)免費(fèi)