下面是一个示例,展示如何使用Next.js和Node.js的TypeScript API来保护应用程序。
首先,安装所需的依赖项。打开终端并运行以下命令:
npm install next express express-session cookie-parser argon2
npm install -D typescript @types/express @types/express-session @types/cookie-parser @types/argon2
接下来,创建一个名为pages/api/login.ts
的文件,用于处理登录请求:
import { NextApiRequest, NextApiResponse } from 'next';
import argon2 from 'argon2';
import { getSession } from 'next-auth/client';
export default async function login(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.status(405).end(); // Method Not Allowed
return;
}
const { username, password } = req.body;
// 验证用户名和密码
const valid = await validateCredentials(username, password);
if (!valid) {
res.status(401).json({ error: 'Invalid credentials' });
return;
}
// 创建会话
const session = await getSession({ req });
session.user = { username }; // 将用户名存储在会话中
res.status(200).json({ message: 'Login successful' });
}
async function validateCredentials(username: string, password: string): Promise {
// 这里可以进行用户名和密码的验证逻辑,比如从数据库中查询用户信息
// 这里使用 argon2 作为密码哈希算法的示例
const hashedPassword = await argon2.hash('correct horse battery staple');
const valid = await argon2.verify(hashedPassword, password);
return valid;
}
然后,创建一个名为pages/api/logout.ts
的文件,用于处理登出请求:
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/client';
export default async function logout(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req });
if (session) {
await session.destroy(); // 销毁会话
}
res.status(200).json({ message: 'Logout successful' });
}
接下来,创建一个名为pages/api/protected.ts
的文件,用于处理受保护的路由:
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/client';
export default async function protectedRoute(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req });
if (!session) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
const { username } = session.user;
res.status(200).json({ message: `Hello, ${username}! This is a protected route.` });
}
最后,修改pages/api/index.ts
文件,将登录和登出的路由添加到API路由中:
import { NextApiRequest, NextApiResponse } from 'next';
import login from './login';
import logout from './logout';
import protectedRoute from './protected';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const { method } = req;
switch (method) {
case 'POST':
return login(req, res);
case 'DELETE':
return logout(req, res);
case 'GET':
return protectedRoute(req, res);
default:
res.status(405).end(); // Method Not Allowed
break;
}
}
现在,你可以在应用程序中使用这些API路由来保护你的应用程序。你可以在需要保护的页面中使用getSession
函数来检查用户是否已登录,并根据需要进行重定向。
希望这个示例能帮助到你!请确保根据自己的需求进行适当的配置和更改。