概览Edge Middleware 可在请求进入应用前完成认证校验。通过签名 Cookie 与 JWT 验证实现路由保护,并在未授权时执行登录重定向,保障一致体验与安全性。middleware.tsimport { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' function verifyJWT(token: string | null): boolean { // 伪实现:生产环境应使用 JWS 验签(RS256/ES256) return Boolean(token && token.split('.').length === 3) } export function middleware(req: NextRequest) { const url = req.nextUrl.clone() const token = req.cookies.get('session')?.value || req.headers.get('authorization')?.replace('Bearer ', '') || null const authed = verifyJWT(token) const protectedPaths = [/^\/dashboard/, /^\/admin/] const isProtected = protectedPaths.some((re) => re.test(url.pathname)) if (isProtected && !authed) { url.pathname = '/login' url.searchParams.set('from', req.nextUrl.pathname) return NextResponse.redirect(url) } return NextResponse.next() } export const config = { matcher: ['/((?!_next|static|api/public).*)'] } 登录后回跳// app/login/page.tsx export default function Login({ searchParams }: { searchParams: { from?: string } }) { const from = searchParams.from || '/dashboard' return ( <form action="/api/login"> <input name="email" /> <button>登录</button> <input type="hidden" name="from" value={from} /> </form> ) } API 设置 Cookie// app/api/login/route.ts import { cookies } from 'next/headers' export async function POST(req: Request) { const body = await req.formData() const from = String(body.get('from') || '/dashboard') cookies().set('session', 'header.payload.signature', { httpOnly: true, path: '/' }) return new Response(null, { status: 302, headers: { Location: from } }) } 治理要点生产环境使用 JWS 验签与短期令牌;敏感路由启用严格校验。Cookie 设置 `httpOnly` 与 `secure`;跨源场景配置 `SameSite`。与日志与观测协同,记录拒绝与重定向事件。验证与指标浏览器:现代浏览器;边缘环境兼容Next.js:15.0+;Edge Runtime:稳定路由保护与重定向可靠;未授权访问清晰可控

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部
1.992707s