接口测试——Cookie、Session、JWT

Cookie与Session的作用

Cookie

定义:

Cookie是存储在用户浏览器中的小数据片段,通常用于保存用户会话信息、偏好设置等。他们由服务器发送给客户端,并由客户端保存。

作用:

  • 保持用户状态:在用户浏览不同页面时维持登录状态或其他个性化设置

  • 追踪用户行为:例如记录用户的访问习惯以进行分析或广告推送

  • 安全特性:可以何止HttpOnly标志防止通过JavaScript访问(减少XSS攻击风险),以及Secure标志确保仅通过HTTPS传输

限制:

每个域名下的Cookie数量和大小有限制;Cookie在每次请求中都会发送到服务器,可能会增加请求的数据量。

解释:

  • 存在哪里?存在本人的浏览器这里

  • 有什么用?

    • 让网站记住你是谁(比如登录状态)

    • 记住你的偏好(比如语言、主题)

  • 举个例子:

    • 登录一个网站之后,下次打开它还记得你是谁,不需要重新登录,这就是Cookie的功劳

  • 缺点:

    • 容量很小(智能存少量的数据)

    • 每次访问网页都会带上它,可能影响速度

    • 如果不安全设置,容易被黑客读取

Session

定义:

Session时一种服务器端技术,用来跟踪用户的状态。当用户访问网站时,服务器为该用户创建一个唯一的session ID,并将此ID存储与cookie中返回给客户端

作用:

  • 管理用户会话:主要用于登陆验证、购物车等功能,能够使被来自同一用户的连续请求

  • 安全性较高:因为session数据存储在服务器上,不像cookie那样容易被篡改

  • 灵活性强:可以存储比cookie更多的信息,且不受浏览器cookie大小的限制

实现方式:

通常使用session ID来关联用户,session数据可以存储在内存、数据或者文件系统中

解释

  • 存在哪里?存在服务器那边(不是本人的电脑里)

  • 有什么用?

    • 网站用来识别你是谁,保存你的登录信息或购物车内容等

  • 举个例子

    • 你在电商网站加购商品,即便没付款,离开页面再回来,购物车还在,这可能是Session在起作用

  • 特点

    • 更安全,因为数据不在本人这里

    • 服务器要负责管理所有用户的Session,压力大一点

你去一家咖啡店,每次来都会另一个小卡片,上面写的你的名字和你喜欢的咖啡口味

这个小卡片就是cookie

还是这家咖啡店,不一样的是,进店时服务员给你一个会员编号,但不会写在卡片上,而是记在他自己的本子上

这个会员编号就是Session ID,服务员本子上的记录就是Session数据

Token认证机制(如JWT)

JSON Web Token(JWT)

定义:

JWT是一种开放标准(RFC 7519),用于在网络应用环境间安全地将信息作为JSON对象传输。通常用于身份验证和信息交换。

结构:

JWT由三部分组成,分别是头部(Header)、载荷(Payload)和签名(Signature)。这三部分用点号(.)分隔。

  • Header:描述令牌类型(即JWT)及所使用的签名算法

  • Payload:包含生命(claims),这些是关于实体(通常是用户)和其他数据的声明(比如用户名、角色、过期时间等)

  • Signature:用来验证消息在传输过程中没有被更改,对于使用私钥签名的令牌,还可以验证发送者的身份(验证这个token是不是真的)

    xxxxx.yyyyy.zzzzz

工作流程:

  • 用户使用用户名/密码登录系统

  • 系统验证凭据后生成JWT并返回给客户端

  • 客户端收到JWT后将其保存(通常在localStorage或sessionStorage中)

  • 后续请求都将携带此JWT到服务器进行身份验证

优点:

  • 无状态:不需要在服务器端保存会话信息,易于扩展

  • 跨域支持:适合分布式架构或多服务架构

  • 安全性:使用HMAC或RSA加密算法保证数据完整性和真实性

注意事项:

  • 保护好密钥:如果签名密钥泄露,则任何人都可以伪造令牌

  • 有效期控制:设置合理的过期时间来限制token的有效性,避免长期有效的安全隐患

  • 存储安全:避免在不安全的地方存储敏感信息,考虑使用HttpOnnly和Secure属性增强安全性

Cookie + Session vs Token(如 JWT)

对比

对比项Cookie + SessionToken(如 JWT)
存储位置浏览器(Cookie)+ 服务器(Session)浏览器(localStorage / sessionStorage)
是否需要服务器存储否(无状态)
是否适合分布式系统不太适合非常适合(跨域、多服务)
安全性中等(需设置 HttpOnly)较高(签名机制)
扩展性一般(Session 多服务器同步麻烦)强(适合微服务架构)

总结:

  • Cookie 是浏览器帮你保存的小纸条;

  • Session 是服务器帮你记的账本,靠 Cookie 来认人;

  • Token(如 JWT) 是你自己带着的电子身份证,走到哪带到哪,服务器一看就知道你是谁。

<think>我们正在处理一个前后端分离项目,前端使用Vue3(TypeScript)+Vite+VueRouter+Pinia+Axios,后端使用NestJS(Fastify)并连接MongoDB(mongoose)和Redis(ioredis)。我们需要实现基于JWTCookieSession的认证机制。以下将分步骤详细说明。###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)项目中实现JWTCookieSession认证机制,以下是完整的实现方案: --- ### 一、后端(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]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值