鉴权接口实战
这一节实现一个最小 JWT 鉴权流程:登录、签发 Token、保护接口、读取当前用户。
示例用户
type User = {
id: string
email: string
password: string
role: 'admin' | 'user'
}
const users: User[] = [
{
id: 'u_1',
email: '[email protected]',
password: 'secret',
role: 'admin',
},
]
示例为了简洁使用明文密码。真实项目必须使用 Argon2、bcrypt 或其他安全哈希方案。
登录接口
import { sign } from 'hono/jwt'
const jwtSecret = 'change-me'
app.post('/auth/login', async (c) => {
const body = await c.req.json<{
email?: string
password?: string
}>()
const user = users.find((item) => item.email === body.email)
if (!user || user.password !== body.password) {
return c.json({ message: 'Invalid email or password' }, 401)
}
const token = await sign(
{
sub: user.id,
role: user.role,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
},
jwtSecret,
)
return c.json({ token })
})
保护路由
import { jwt } from 'hono/jwt'
app.use(
'/auth/me',
jwt({
secret: jwtSecret,
}),
)
app.get('/auth/me', (c) => {
const payload = c.get('jwtPayload')
const user = users.find((item) => item.id === payload.sub)
if (!user) {
return c.json({ message: 'User not found' }, 404)
}
return c.json({
id: user.id,
email: user.email,
role: user.role,
})
})
调用流程
登录:
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"secret"}'
访问当前用户:
curl http://localhost:3000/auth/me \
-H "Authorization: Bearer <token>"
生产改进
- 使用密码哈希,不保存明文密码。
- 使用 HTTPS,避免 Token 在传输中泄露。
- Token 密钥通过环境变量或 Secret 管理。
- 设计刷新 Token、退出登录和吊销机制。
- 对登录接口加限流和审计日志。
- 不要在 Token 中放敏感资料。
JWT 适合无状态 API,但无状态不等于无需管理。权限变更、账号禁用、风险登录等场景仍然需要服务端策略。
相关内容
- Hono 是什么 介绍 Hono 的定位、核心特点、Web Standards 思路、多运行时能力,以及它与传统 Node.js Web 框架的差异。
- 安装和 Hello World 学习使用 create-hono 创建 Hono 项目,分别了解通用模板和 Node.js 模板的 Hello World 写法。
- 运行时选择 对比 Hono 在 Node.js、Cloudflare Workers、Bun、Deno 等运行时中的入口写法、部署方式和适用场景。
- 路由基础 学习 Hono 的 GET、POST、动态参数、通配符、路由分组和模块化路由写法。
- Context 详解 介绍 Hono Context 的 req、json、text、html、redirect、header、status、set、get 等常用 API。
- 中间件机制 学习 Hono 中间件的执行顺序、自定义中间件写法、路径匹配、next 调用和常见使用场景。