auth0-nuxt
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Nuxt SDK
Auth0 Nuxt SDK
Overview
概述
Server-side session authentication for Nuxt 3/4. NOT the same as @auth0/auth0-vue (client-side SPA).
Core principle: Uses server-side encrypted cookie sessions, not client-side tokens.
为Nuxt 3/4提供服务端会话认证。与@auth0/auth0-vue(客户端SPA专用)不同。
核心原则: 使用服务端加密Cookie会话,而非客户端令牌。
When to Use
适用场景
Use this when:
- Building Nuxt 3/4 applications with server-side rendering (Node.js 20 LTS+)
- Need secure session management with encrypted cookies
- Protecting server routes and API endpoints
- Accessing Auth0 Management API or custom APIs
Don't use this when:
- Using Nuxt 2 (not supported - use different Auth0 SDK)
- Building pure client-side SPA without server (use @auth0/auth0-vue instead)
- Using non-Auth0 authentication provider
- Static site generation only (SSG) without server runtime
在以下场景使用:
- 构建基于服务端渲染的Nuxt 3/4应用(要求Node.js 20 LTS+)
- 需要通过加密Cookie实现安全的会话管理
- 保护服务端路由与API端点
- 访问Auth0管理API或自定义API
请勿在以下场景使用:
- 使用Nuxt 2(不支持,请使用其他Auth0 SDK)
- 构建无服务端的纯客户端SPA(请改用@auth0/auth0-vue)
- 使用非Auth0的认证提供商
- 仅进行静态站点生成(SSG)且无服务端运行时
Critical Mistakes to Avoid
需避免的常见错误
| Mistake | Solution |
|---|---|
Installing | Use |
| Auth0 app type "Single Page Application" | Use "Regular Web Application" |
Env vars: | Use |
Using | Use |
| Missing callback URLs in Auth0 Dashboard | Add |
| Weak/missing session secret | Generate: |
| 错误 | 解决方案 |
|---|---|
安装 | 使用 |
| Auth0应用类型选择“Single Page Application” | 选择“Regular Web Application” |
环境变量使用 | 使用 |
使用 | 在服务端使用 |
| Auth0控制台中缺少回调URL | 添加 |
| 会话密钥强度不足或缺失 | 生成方式: |
Quick Setup
快速设置
bash
undefinedbash
undefined1. Install
1. 安装
npm install @auth0/auth0-nuxt
npm install @auth0/auth0-nuxt
2. Generate secret
2. 生成密钥
openssl rand -hex 64
```bashopenssl rand -hex 64
```bash3. .env
3. .env文件配置
NUXT_AUTH0_DOMAIN=your-tenant.auth0.com
NUXT_AUTH0_CLIENT_ID=your-client-id
NUXT_AUTH0_CLIENT_SECRET=your-client-secret
NUXT_AUTH0_SESSION_SECRET=<from-openssl>
NUXT_AUTH0_APP_BASE_URL=http://localhost:3000
NUXT_AUTH0_AUDIENCE=https://your-api # optional
```typescript
// 4. nuxt.config.ts
export default defineNuxtConfig({
modules: ['@auth0/auth0-nuxt'],
runtimeConfig: {
auth0: {
domain: '',
clientId: '',
clientSecret: '',
sessionSecret: '',
appBaseUrl: 'http://localhost:3000',
audience: '', // optional
},
},
})NUXT_AUTH0_DOMAIN=your-tenant.auth0.com
NUXT_AUTH0_CLIENT_ID=your-client-id
NUXT_AUTH0_CLIENT_SECRET=your-client-secret
NUXT_AUTH0_SESSION_SECRET=<from-openssl>
NUXT_AUTH0_APP_BASE_URL=http://localhost:3000
NUXT_AUTH0_AUDIENCE=https://your-api # 可选
```typescript
// 4. nuxt.config.ts配置
export default defineNuxtConfig({
modules: ['@auth0/auth0-nuxt'],
runtimeConfig: {
auth0: {
domain: '',
clientId: '',
clientSecret: '',
sessionSecret: '',
appBaseUrl: 'http://localhost:3000',
audience: '', // 可选
},
},
})Built-in Routes
内置路由
The SDK automatically mounts these routes:
| Route | Method | Purpose |
|---|---|---|
| GET | Initiates login flow. Supports |
| GET | Handles Auth0 callback after login |
| GET | Logs user out and redirects to Auth0 logout |
| POST | Receives logout tokens for back-channel logout |
Customize: Pass or to module config.
routes: { login, callback, logout, backchannelLogout }mountRoutes: false该SDK会自动挂载以下路由:
| 路由 | 请求方法 | 用途 |
|---|---|---|
| GET | 启动登录流程,支持 |
| GET | 处理登录后的Auth0回调 |
| GET | 登出用户并重定向至Auth0登出页面 |
| POST | 接收登出令牌以实现后端通道登出 |
自定义配置: 在模块配置中传入或设置。
routes: { login, callback, logout, backchannelLogout }mountRoutes: falseComposables
组合式函数
| Composable | Context | Usage |
|---|---|---|
| Server-side | Access |
| Client-side | Display user data only. Never use for security checks |
typescript
// Server example
const auth0 = useAuth0(event);
const session = await auth0.getSession();vue
<script setup>
const user = useUser();
</script>
<template>
<div v-if="user">Welcome {{ user.name }}</div>
<template>| 组合式函数 | 上下文 | 用途 |
|---|---|---|
| 服务端 | 调用 |
| 客户端 | 仅用于展示用户数据。绝不能用于安全校验 |
typescript
// 服务端示例
const auth0 = useAuth0(event);
const session = await auth0.getSession();vue
<script setup>
const user = useUser();
</script>
<template>
<div v-if="user">Welcome {{ user.name }}</div>
<template>Protecting Routes
路由保护
Three layers: Route middleware (client), server middleware (SSR), API guards.
typescript
// middleware/auth.ts - Client navigation
export default defineNuxtRouteMiddleware((to) => {
if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});typescript
// server/middleware/auth.server.ts - SSR protection
export default defineEventHandler(async (event) => {
const url = getRequestURL(event);
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
return sendRedirect(event, `/auth/login?returnTo=${url.pathname}`);
}
});typescript
// server/api/protected.ts - API endpoint protection
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized'
});
}
return { data: 'protected data' };
});For role-based, permission-based, and advanced patterns: route-protection.md
三层保护: 路由中间件(客户端)、服务端中间件(SSR)、API守卫。
typescript
// middleware/auth.ts - 客户端导航保护
export default defineNuxtRouteMiddleware((to) => {
if (!useUser().value) return navigateTo(`/auth/login?returnTo=${to.path}`);
});typescript
// server/middleware/auth.server.ts - SSR保护
export default defineEventHandler(async (event) => {
const url = getRequestURL(event);
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
return sendRedirect(event, `/auth/login?returnTo=${url.pathname}`);
}
});typescript
// server/api/protected.ts - API端点保护
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const session = await auth0Client.getSession();
if (!session) {
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized'
});
}
return { data: 'protected data' };
});如需基于角色、权限的高级保护模式: 参考route-protection.md
Session Management
会话管理
Stateless (Default)
无状态(默认)
Uses encrypted, chunked cookies. No configuration needed.
使用加密的分块Cookie,无需额外配置。
Stateful (Redis, MongoDB, etc.)
有状态(Redis、MongoDB等)
For larger sessions or distributed systems:
typescript
// nuxt.config.ts
modules: [
['@auth0/auth0-nuxt', {
sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
}]
]For complete session store implementations, see: session-stores.md
适用于会话数据较大或分布式系统:
typescript
// nuxt.config.ts
modules: [
['@auth0/auth0-nuxt', {
sessionStoreFactoryPath: '~/server/utils/session-store-factory.ts'
}]
]完整的会话存储实现示例,请参考: session-stores.md
API Integration
API集成
Configure audience for API access tokens:
typescript
// nuxt.config.ts
runtimeConfig: {
auth0: {
audience: 'https://your-api-identifier',
}
}Retrieve tokens server-side:
typescript
// server/api/call-api.ts
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const { accessToken } = await auth0Client.getAccessToken();
return await $fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
});配置受众以获取API访问令牌:
typescript
// nuxt.config.ts
runtimeConfig: {
auth0: {
audience: 'https://your-api-identifier',
}
}在服务端获取令牌:
typescript
// server/api/call-api.ts
export default defineEventHandler(async (event) => {
const auth0Client = useAuth0(event);
const { accessToken } = await auth0Client.getAccessToken();
return await $fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
});Security Checklist
安全检查清单
- ✅ Server-side validation only (never trust )
useUser() - ✅ HTTPS in production
- ✅ Strong session secret ()
openssl rand -hex 64 - ✅ Never commit files
.env - ✅ Stateful sessions for PII/large data
- ✅ 仅在服务端进行校验(绝不要信任)
useUser() - ✅ 生产环境使用HTTPS
- ✅ 使用高强度会话密钥(生成)
openssl rand -hex 64 - ✅ 绝不提交文件到版本控制
.env - ✅ 对于包含个人身份信息(PII)或较大数据的会话,使用有状态会话存储
Troubleshooting
故障排查
| Error | Solution |
|---|---|
| "Module not found" | Install |
| "Missing domain/clientId/clientSecret" | Check |
| "Redirect URI mismatch" | Match Auth0 Dashboard callback to |
| "useAuth0 is not defined" | Use only in server context with H3 event object |
| Cookies too large | Use stateful sessions or reduce scopes |
| 错误 | 解决方案 |
|---|---|
| "Module not found" | 安装 |
| "Missing domain/clientId/clientSecret" | 检查环境变量是否使用 |
| "Redirect URI mismatch" | 确保Auth0控制台中的回调URL与 |
| "useAuth0 is not defined" | 仅在服务端上下文并传入H3 event对象时使用 |
| Cookies过大 | 使用有状态会话或减少授权范围(scopes) |
Additional Resources
额外资源
Guides: Route Protection Patterns • Custom Session Stores • Common Examples
指南: 路由保护模式 • 自定义会话存储 • 常见示例