
模型压缩四剑客:量化、剪枝、蒸馏、二值化
欢迎来到API认证与JSON Web Tokens(JWT)详解!本文我们将深入探讨如何使用JWT进行API认证,以及如何保护API路由。让我们开始吧!
在现代Web应用中,API认证是确保应用安全的关键步骤。通过JSON Web Tokens(JWT),我们可以有效地保护API路由,确保只有经过认证的用户才能访问特定资源。
为了实现这一目标,我们将使用以下技术栈:
首先,创建一个项目文件夹并初始化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