<think>我们正在处理一个前后端分离项目,前端使用Vue3(TypeScript)+Vite+VueRouter+Pinia+Axios,后端使用NestJS(Fastify)并连接MongoDB(mongoose)和Redis(ioredis)。我们需要实现基于JWT、Cookie和Session的认证机制。以下将分步骤详细说明。###1.后端(NestJS)实现JWT认证与Session管理####1.1安装依赖```bashnpminstall@nestjs/jwt@nestjs/passportpassportpassport-jwtfastify-session@fastify/secure-session```####1.2JWT模块配置```typescript//auth/jwt.strategy.tsimport{Injectable}from'@nestjs/common';import{PassportStrategy}from'@nestjs/passport';import{ExtractJwt,Strategy}from'passport-jwt';import{ConfigService}from'@nestjs/config';@Injectable()exportclassJwtStrategyextendsPassportStrategy(Strategy){constructor(privateconfigService:ConfigService){super({jwtFromRequest:ExtractJwt.fromExtractors([(request:FastifyRequest)=>{returnrequest.cookies?.access_token;//从Cookie中提取}]),ignoreExpiration:false,secretOrKey:configService.get<string>('JWT_SECRET'),});}asyncvalidate(payload:any){return{userId:payload.sub,username:payload.username};}}```####1.3登录接口生成JWT并设置Cookie```typescript//auth/auth.service.tsimport{Injectable}from'@nestjs/common';import{JwtService}from'@nestjs/jwt';import{FastifyReply}from'fastify';@Injectable()exportclassAuthService{constructor(privatejwtService:JwtService){}asynclogin(user:any,reply:FastifyReply){constpayload={sub:user.id,username:user.username};constaccessToken=this.jwtService.sign(payload);//设置Cookiereply.setCookie('access_token',accessToken,{httpOnly:true,secure:process.env.NODE_ENV==='production',path:'/',maxAge:86400//1天});return{accessToken};}}```####1.4使用Redis存储Session(可选,用于扩展会话管理)```typescript//main.ts(NestJS入口)importfastifySessionfrom'@fastify/secure-session';asyncfunctionbootstrap(){//...之前代码awaitapp.register(fastifySession,{secret:'averylogphrasebiggerthanthirtytwochars',salt:'mq9hDxBVDbspDR6n',cookie:{path:'/',httpOnly:true,secure:false,//生产环境下应为truemaxAge:86400}});}```###2.前端(Vue3)处理认证流程####2.1Axios配置(携带Cookie)```typescript//src/utils/api.tsimportaxiosfrom'axios';constapi=axios.create({baseURL:import.meta.env.VITE_API_BASE,timeout:10000,withCredentials:true//允许跨域携带Cookie});//请求拦截器:添加Token(可选,因为Cookie会自动发送)api.interceptors.request.use(config=>{//如果同时使用Authorization头,可以这样设置consttoken=localStorage.getItem('access_token');if(token){config.headers.Authorization=`Bearer${token}`;}returnconfig;});exportdefaultapi;```####2.2Pinia存储用户状态```typescript//src/stores/authStore.tsimport{defineStore}from'pinia';importapifrom'@/utils/api';interfaceUser{id:string;username:string;email:string;}exportconstuseAuthStore=defineStore('auth',{state:()=>({user:nullasUser|null,isAuthenticated:false}),actions:{asynclogin(credentials:{username:string;password:string}){try{constresponse=awaitapi.post('/auth/login',credentials);//如果需要,可以存储token到localStorage(但Cookie已由浏览器自动存储)//localStorage.setItem('access_token',response.data.accessToken);this.user=response.data.user;this.isAuthenticated=true;}catch(error){console.error('登录失败',error);throwerror;}},asynclogout(){awaitapi.post('/auth/logout');this.user=null;this.isAuthenticated=false;//清除本地存储的token(如果存储了)localStorage.removeItem('access_token');},asynccheckAuth(){try{const{data}=awaitapi.get('/auth/profile');this.user=data;this.isAuthenticated=true;}catch(error){this.isAuthenticated=false;}}}});```####2.3路由守卫(VueRouter)```typescript//src/router/index.tsimport{createRouter,createWebHistory}from'vue-router';import{useAuthStore}from'@/stores/authStore';constroutes=[{path:'/',component:()=>import('@/views/Home.vue')},{path:'/login',component:()=>import('@/views/Login.vue')},{path:'/profile',component:()=>import('@/views/Profile.vue'),meta:{requiresAuth:true}}];constrouter=createRouter({history:createWebHistory(),routes});router.beforeEach(async(to,from,next)=>{constauthStore=useAuthStore();//检查是否需要认证if(to.meta.requiresAuth){//如果尚未检查过认证状态,则检查if(!authStore.isAuthenticated){try{awaitauthStore.checkAuth();}catch(error){//忽略错误,会在下面处理}}if(authStore.isAuthenticated){next();}else{next('/login');}}else{next();}});exportdefaultrouter;```###3.前后端认证流程整合1.**登录流程**:-用户在前端提交登录表单(用户名/密码)-前端通过Axios发送POST请求到`/auth/login`-后端验证凭证,生成JWT并设置到Cookie(HttpOnly,Secure)-同时可以返回用户信息(避免敏感信息)2.**后续请求**:-浏览器自动在每次请求中携带Cookie-后端通过`JwtStrategy`验证Cookie中的JWT-验证通过后,请求处理继续3.**退出登录**:-前端调用`/auth/logout`接口-后端清除Session(如果使用)并清除Cookie-前端清除本地用户状态4.**认证检查**:-前端在路由守卫中调用`/auth/profile`(受保护端点)-后端验证JWT并返回当前用户信息-前端更新认证状态###4.安全增强措施-**HttpOnlyCookie**:防止XSS攻击获取Token-**SecureCookie**:生产环境中启用,仅通过HTTPS传输-**SameSite属性**:设置为`Lax`或`Strict`防止CSRF攻击-**JWT有效期**:设置较短的有效期(如15分钟)并配合刷新令牌机制-**CORS限制**:仅允许信任的源(如`http://localhost:5173`)###5.常见问题解决**问题:跨域请求中Cookie未携带**-确保后端CORS配置允许凭证(`credentials:true`)-前端Axios设置`withCredentials:true`-后端设置Cookie时指定`SameSite=None`和`Secure`(HTTPS环境下)**问题:刷新页面后Vuex/Pinia状态丢失**-使用`checkAuth`方法在应用初始化时重新获取用户状态-将必要信息存储在`localStorage`(非敏感信息)或Cookie中**问题:JWT过期处理**-实现刷新令牌机制:前端在收到401错误后,使用刷新令牌获取新访问令牌-刷新令牌应具有更长有效期,且存储更安全(HttpOnlyCookie)###总结通过以上步骤,我们实现了:1.后端生成JWT并设置HttpOnlyCookie2.前端自动携带Cookie进行API请求3.Pinia管理用户认证状态4.VueRouter路由守卫保护需要认证的页面5.安全措施保障认证过程的安全性这种模式结合了JWT的无状态特性和Cookie的自动管理优势,同时通过HttpOnly标志增强了安全性。§§相关问题§§1.如何在NestJS中实现JWT刷新令牌机制?2.Vue3中如何安全地存储和刷新JWT令牌?3.如何在前端实现无感刷新令牌?4.在NestJS中如何同时支持Cookie和Authorization头两种认证方式?5.如何测试Vue组件中依赖于认证状态的逻辑?6.在Fastify中如何配置安全的Cookie参数?</think>### Vue3 + NestJS(Fastify) JWT认证集成指南
我将详细说明如何在Vue3和NestJS(Fastify)项目中实现JWT、Cookie和Session认证机制,以下是完整的实现方案:
---
### 一、后端(NestJS)实现
#### 1. JWT认证模块
```typescript
// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '1h' }
})
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController]
})
export class AuthModule {}
```
#### 2. JWT策略与守卫
```typescript
// src/auth/jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { FastifyRequest } from 'fastify';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(request: FastifyRequest) => {
return request.cookies?.access_token; // 从Cookie获取JWT
}
]),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
```
#### 3. 登录接口实现
```typescript
// src/auth/auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { FastifyReply } from 'fastify';
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}
async login(user: any, reply: FastifyReply) {
const payload = { sub: user.id, username: user.username };
const accessToken = this.jwtService.sign(payload);
// 设置HttpOnly Cookie
reply.setCookie('access_token', accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
maxAge: 3600 // 1小时
});
// Redis存储会话信息
await redis.set(`session:${user.id}`, JSON.stringify(user), 'EX', 3600);
return { accessToken };
}
}
```
#### 4. 会话保护路由
```typescript
// src/users/users.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
@Controller('users')
export class UsersController {
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Req() req) {
// 从Redis获取完整会话数据
return redis.get(`session:${req.user.userId}`);
}
}
```
---
### 二、前端(Vue3)实现
#### 1. Axios配置(处理Cookie)
```typescript
// src/utils/api.ts
import axios from 'axios';
const api = axios.create({
baseURL: import.meta.env.VITE_API_BASE,
timeout: 10000,
withCredentials: true // 关键:允许跨域发送Cookie
});
// 请求拦截器
api.interceptors.request.use(config => {
// 从Pinia获取token(备用方案)
const authStore = useAuthStore();
if (authStore.accessToken) {
config.headers.Authorization = `Bearer ${authStore.accessToken}`;
}
return config;
});
// 响应拦截器(处理401错误)
api.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
const authStore = useAuthStore();
authStore.logout();
router.push('/login');
}
return Promise.reject(error);
}
);
export default api;
```
#### 2. Pinia认证存储
```typescript
// src/stores/authStore.ts
import { defineStore } from 'pinia';
import api from '@/utils/api';
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null as any,
accessToken: '',
isAuthenticated: false
}),
actions: {
async login(credentials: { username: string; password: string }) {
try {
const response = await api.post('/auth/login', credentials);
this.isAuthenticated = true;
this.user = response.data.user;
// 注意:JWT通过Cookie存储,此处仅存储用户数据
} catch (error) {
throw new Error('登录失败');
}
},
async checkAuth() {
try {
const { data } = await api.get('/users/profile');
this.user = data;
this.isAuthenticated = true;
return true;
} catch {
this.logout();
return false;
}
},
logout() {
api.post('/auth/logout');
this.user = null;
this.isAuthenticated = false;
router.push('/login');
}
}
});
```
#### 3. 路由守卫实现
```typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/authStore';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/login', component: () => import('@/views/Login.vue') },
{
path: '/profile',
component: () => import('@/views/Profile.vue'),
meta: { requiresAuth: true }
}
]
});
router.beforeEach(async (to) => {
const authStore = useAuthStore();
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
// 先尝试静默认证
const isAuthenticated = await authStore.checkAuth();
if (!isAuthenticated) return '/login';
}
});
export default router;
```
#### 4. 登录组件示例
```vue
<!-- src/views/Login.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { useAuthStore } from '@/stores/authStore';
const authStore = useAuthStore();
const username = ref('');
const password = ref('');
const error = ref('');
const handleLogin = async () => {
try {
await authStore.login({
username: username.value,
password: password.value
});
router.push('/profile');
} catch (err) {
error.value = '用户名或密码错误';
}
};
</script>
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="用户名">
<input v-model="password" type="password" placeholder="密码">
<button type="submit">登录</button>
<p v-if="error" class="error">{{ error }}</p>
</form>
</template>
```
---
### 三、安全增强措施
1. **Cookie安全配置**:
```typescript
// NestJS Cookie设置
reply.setCookie('access_token', token, {
httpOnly: true, // 防止XSS攻击
secure: true, // 仅HTTPS传输
sameSite: 'strict',// 防止CSRF攻击
path: '/',
maxAge: 3600
});
```
2. **Redis会话管理**:
```typescript
// 存储会话
await redis.setex(`session:${userId}`, 3600, JSON.stringify(userData));
// 验证会话
async validateSession(userId: string) {
const session = await redis.get(`session:${userId}`);
return session ? JSON.parse(session) : null;
}
```
3. **JWT刷新机制**:
```typescript
// 前端静默刷新
api.interceptors.response.use(null, async (error) => {
if (error.response.status === 401 && !error.config._retry) {
error.config._retry = true;
await authStore.refreshToken();
return api(error.config);
}
return Promise.reject(error);
});
```
---
### 四、工作流程说明
1. **登录流程**:
- 用户提交登录表单
- Vue发送POST `/auth/login`
- NestJS验证凭证,生成JWT
- 设置HttpOnly Cookie并存储Redis会话
- 返回用户数据(不含敏感信息)
2. **认证流程**:
- 前端发起请求自动携带Cookie
- NestJS从Cookie提取JWT验证
- 验证成功后从Redis获取完整会话数据
- 返回请求的资源
3. **登出流程**:
- 调用`/auth/logout`清除服务端会话
- 清除客户端Pinia状态
- 服务端清除Redis会话
---
### 五、最佳实践建议
1. **Cookie vs LocalStorage**:
- 使用HttpOnly Cookie存储JWT更安全
- 避免XSS攻击窃取令牌
- 配合SameSite和Secure属性
2. **会话过期处理**:
```typescript
// 前端定期检查会话
setInterval(() => {
if (authStore.isAuthenticated) {
authStore.checkAuth();
}
}, 300000); // 每5分钟
```
3. **敏感操作保护**:
```typescript
// 关键操作需要二次验证
@Post('change-password')
@UseGuards(JwtAuthGuard, TwoFactorGuard)
async changePassword() {
// ...
}
```
4. **监控与日志**:
- 记录所有认证相关操作
- 监控异常登录尝试
- 实现会话设备管理
此方案结合了JWT的无状态特性和Redis会话管理的灵活性,通过HttpOnly Cookie实现安全认证,适合生产环境部署[^1][^2]。