实现步骤
- 安装依赖:确保项目中安装了
next
和cookie-parser
(如果使用Cookie相关操作)等必要依赖。
- 创建中间件:在
lib
目录(可自定义)下创建一个用于基础认证的中间件文件,比如basic-auth-middleware.js
。
- 在API Routes中使用中间件:在需要认证的API Route文件中引入并使用该中间件。
关键代码示例
- basic-auth-middleware.js
import { NextApiRequest, NextApiResponse } from 'next';
const basicAuthMiddleware = (req: NextApiRequest, res: NextApiResponse, next: () => void) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ error: 'Authorization header is missing' });
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
// 替换为实际的用户名和密码验证逻辑
const validUsername = 'your-username';
const validPassword = 'your-password';
if (username === validUsername && password === validPassword) {
next();
} else {
return res.status(401).json({ error: 'Invalid credentials' });
}
};
export default basicAuthMiddleware;
- 在API Route中使用
假设在
pages/api/some-protected-route.js
中使用:
import type { NextApiRequest, NextApiResponse } from 'next';
import basicAuthMiddleware from '../../lib/basic-auth-middleware';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
basicAuthMiddleware(req, res, () => {
// 认证通过后的业务逻辑
res.status(200).json({ message: 'Authenticated successfully' });
});
}