1.3 Session和Cookie

本文深入讲解了Session和Cookie的工作原理及应用场景,对比了两者之间的主要区别,并提供了前端保存用户信息的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.3 Session和Cookie
1.3.1 Session介绍
Session:在计算机中,尤其是在网络应用中,称为“会话控制”。Session对象存储特定用户会话所需的属性及配置信息。这样,当用户在应用程序的Web页之间跳转时,存储在Session对象中的变量将不会丢失,而是在整个用户会话中一直存在下去。当用户请求来自应用程序的 Web页时,如果该用户还没有会话,则Web服务器将自动创建一个 Session对象。当会话过期或被放弃后,服务器将终止该会话。Session 对象最常见的一个用法就是存储用户的首选项。例如,如果用户指明不喜欢查看图形,就可以将该信息存储在Session对象中。有关使用Session 对象的详细信息,请参阅“ASP应用程序”部分的“管理会话”。注意会话状态仅在支持cookie的浏览器中保留。

小结:
1.Session称之为 “会话机制”
2.在浏览器中打开网页 就是一个会话.
3.用户的数据可以保存到会话中,但是有生命周期. 当会话关闭,则数据消失.

1.3.2 Cookie机制
Cookie,有时也用其复数形式 Cookies。类型为“小型文本文件”,是某些网站为了辨别用户身份,进行Session跟踪而储存在用户本地终端上的数据(通常经过加密),由用户客户端计算机暂时或永久保存的信息 [1] 。
说明:
1.cookie是一个小型的文本文件
2.cookie中存储的数据一般都是密文.
3.cookie中的数据的生命周期可控. 几天.几年!!!

1.3.3 session和cookie区别
1.session的数据是临时存储.cookie的数据可以永久保存. (生命周期不同)
2.sesion是浏览器中的一个内存对象!而cookie是一个实际的本地文件. (形式不同).
3.session一般存储是一些涉密数据.cookie一般存储相对公开的数据(免密登录). (安全性)

1.4 前端保存用户信息
login(){
      //获取表单对象之后进行数据校验
      //valid 表示校验的结果 true表示通过  false表示失败
      this.$refs.loginFormRef.validate(async valid => {
         //如果没有完成校验则直接返回
         if(!valid) return

        //如果校验成功,则发起ajax请求
        const {data: result} = await this.$http.post('/user/login',this.loginForm)
        if(result.status !== 200) return this.$message.error("用户登录失败")
        this.$message.success("用户登录成功")

        //获取用户token信息
        let token = result.data
        window.sessionStorage.setItem("token",token)

        //用户登录成功之后,跳转到home页面
        this.$router.push("/home")
      })
    }
 

<think>我们正在处理一个前后端分离项目,前端使用Vue3(TypeScript)+Vite+VueRouter+Pinia+Axios,后端使用NestJS(Fastify)并连接MongoDB(mongoose)Redis(ioredis)。我们需要实现基于JWT、CookieSession的认证机制。以下将分步骤详细说明。###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&#39;@nestjs/common&#39;;import{PassportStrategy}from&#39;@nestjs/passport&#39;;import{ExtractJwt,Strategy}from&#39;passport-jwt&#39;;import{ConfigService}from&#39;@nestjs/config&#39;;@Injectable()exportclassJwtStrategyextendsPassportStrategy(Strategy){constructor(privateconfigService:ConfigService){super({jwtFromRequest:ExtractJwt.fromExtractors([(request:FastifyRequest)=>{returnrequest.cookies?.access_token;//从Cookie中提取}]),ignoreExpiration:false,secretOrKey:configService.get<string>(&#39;JWT_SECRET&#39;),});}asyncvalidate(payload:any){return{userId:payload.sub,username:payload.username};}}```####1.3登录接口生成JWT并设置Cookie```typescript//auth/auth.service.tsimport{Injectable}from&#39;@nestjs/common&#39;;import{JwtService}from&#39;@nestjs/jwt&#39;;import{FastifyReply}from&#39;fastify&#39;;@Injectable()exportclassAuthService{constructor(privatejwtService:JwtService){}asynclogin(user:any,reply:FastifyReply){constpayload={sub:user.id,username:user.username};constaccessToken=this.jwtService.sign(payload);//设置Cookiereply.setCookie(&#39;access_token&#39;,accessToken,{httpOnly:true,secure:process.env.NODE_ENV===&#39;production&#39;,path:&#39;/&#39;,maxAge:86400//1天});return{accessToken};}}```####1.4使用Redis存储Session(可选,用于扩展会话管理)```typescript//main.ts(NestJS入口)importfastifySessionfrom&#39;@fastify/secure-session&#39;;asyncfunctionbootstrap(){//...之前代码awaitapp.register(fastifySession,{secret:&#39;averylogphrasebiggerthanthirtytwochars&#39;,salt:&#39;mq9hDxBVDbspDR6n&#39;,cookie:{path:&#39;/&#39;,httpOnly:true,secure:false,//生产环境下应为truemaxAge:86400}});}```###2.前端(Vue3)处理认证流程####2.1Axios配置(携带Cookie)```typescript//src/utils/api.tsimportaxiosfrom&#39;axios&#39;;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(&#39;access_token&#39;);if(token){config.headers.Authorization=`Bearer${token}`;}returnconfig;});exportdefaultapi;```####2.2Pinia存储用户状态```typescript//src/stores/authStore.tsimport{defineStore}from&#39;pinia&#39;;importapifrom&#39;@/utils/api&#39;;interfaceUser{id:string;username:string;email:string;}exportconstuseAuthStore=defineStore(&#39;auth&#39;,{state:()=>({user:nullasUser|null,isAuthenticated:false}),actions:{asynclogin(credentials:{username:string;password:string}){try{constresponse=awaitapi.post(&#39;/auth/login&#39;,credentials);//如果需要,可以存储token到localStorage(但Cookie已由浏览器自动存储)//localStorage.setItem(&#39;access_token&#39;,response.data.accessToken);this.user=response.data.user;this.isAuthenticated=true;}catch(error){console.error(&#39;登录失败&#39;,error);throwerror;}},asynclogout(){awaitapi.post(&#39;/auth/logout&#39;);this.user=null;this.isAuthenticated=false;//清除本地存储的token(如果存储了)localStorage.removeItem(&#39;access_token&#39;);},asynccheckAuth(){try{const{data}=awaitapi.get(&#39;/auth/profile&#39;);this.user=data;this.isAuthenticated=true;}catch(error){this.isAuthenticated=false;}}}});```####2.3路由守卫(VueRouter)```typescript//src/router/index.tsimport{createRouter,createWebHistory}from&#39;vue-router&#39;;import{useAuthStore}from&#39;@/stores/authStore&#39;;constroutes=[{path:&#39;/&#39;,component:()=>import(&#39;@/views/Home.vue&#39;)},{path:&#39;/login&#39;,component:()=>import(&#39;@/views/Login.vue&#39;)},{path:&#39;/profile&#39;,component:()=>import(&#39;@/views/Profile.vue&#39;),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(&#39;/login&#39;);}}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中如何同时支持CookieAuthorization头两种认证方式?5.如何测试Vue组件中依赖于认证状态的逻辑?6.在Fastify中如何配置安全的Cookie参数?</think>### Vue3 + NestJS(Fastify) JWT认证集成指南 我将详细说明如何在Vue3NestJS(Fastify)项目中实现JWT、CookieSession认证机制,以下是完整的实现方案: --- ### 一、后端(NestJS)实现 #### 1. JWT认证模块 ```typescript // src/auth/auth.module.ts import { Module } from &#39;@nestjs/common&#39;; import { JwtModule } from &#39;@nestjs/jwt&#39;; import { AuthService } from &#39;./auth.service&#39;; import { AuthController } from &#39;./auth.controller&#39;; import { JwtStrategy } from &#39;./jwt.strategy&#39;; @Module({ imports: [ JwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: &#39;1h&#39; } }) ], providers: [AuthService, JwtStrategy], controllers: [AuthController] }) export class AuthModule {} ``` #### 2. JWT策略与守卫 ```typescript // src/auth/jwt.strategy.ts import { Injectable } from &#39;@nestjs/common&#39;; import { PassportStrategy } from &#39;@nestjs/passport&#39;; import { ExtractJwt, Strategy } from &#39;passport-jwt&#39;; import { FastifyRequest } from &#39;fastify&#39;; @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 &#39;@nestjs/common&#39;; import { JwtService } from &#39;@nestjs/jwt&#39;; import { FastifyReply } from &#39;fastify&#39;; @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(&#39;access_token&#39;, accessToken, { httpOnly: true, secure: process.env.NODE_ENV === &#39;production&#39;, path: &#39;/&#39;, maxAge: 3600 // 1小时 }); // Redis存储会话信息 await redis.set(`session:${user.id}`, JSON.stringify(user), &#39;EX&#39;, 3600); return { accessToken }; } } ``` #### 4. 会话保护路由 ```typescript // src/users/users.controller.ts import { Controller, Get, UseGuards } from &#39;@nestjs/common&#39;; import { JwtAuthGuard } from &#39;../auth/jwt-auth.guard&#39;; @Controller(&#39;users&#39;) export class UsersController { @UseGuards(JwtAuthGuard) @Get(&#39;profile&#39;) getProfile(@Req() req) { // 从Redis获取完整会话数据 return redis.get(`session:${req.user.userId}`); } } ``` --- ### 二、前端(Vue3)实现 #### 1. Axios配置(处理Cookie) ```typescript // src/utils/api.ts import axios from &#39;axios&#39;; 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(&#39;/login&#39;); } return Promise.reject(error); } ); export default api; ``` #### 2. Pinia认证存储 ```typescript // src/stores/authStore.ts import { defineStore } from &#39;pinia&#39;; import api from &#39;@/utils/api&#39;; export const useAuthStore = defineStore(&#39;auth&#39;, { state: () => ({ user: null as any, accessToken: &#39;&#39;, isAuthenticated: false }), actions: { async login(credentials: { username: string; password: string }) { try { const response = await api.post(&#39;/auth/login&#39;, credentials); this.isAuthenticated = true; this.user = response.data.user; // 注意:JWT通过Cookie存储,此处仅存储用户数据 } catch (error) { throw new Error(&#39;登录失败&#39;); } }, async checkAuth() { try { const { data } = await api.get(&#39;/users/profile&#39;); this.user = data; this.isAuthenticated = true; return true; } catch { this.logout(); return false; } }, logout() { api.post(&#39;/auth/logout&#39;); this.user = null; this.isAuthenticated = false; router.push(&#39;/login&#39;); } } }); ``` #### 3. 路由守卫实现 ```typescript // src/router/index.ts import { createRouter, createWebHistory } from &#39;vue-router&#39;; import { useAuthStore } from &#39;@/stores/authStore&#39;; const router = createRouter({ history: createWebHistory(), routes: [ { path: &#39;/login&#39;, component: () => import(&#39;@/views/Login.vue&#39;) }, { path: &#39;/profile&#39;, component: () => import(&#39;@/views/Profile.vue&#39;), meta: { requiresAuth: true } } ] }); router.beforeEach(async (to) => { const authStore = useAuthStore(); if (to.meta.requiresAuth && !authStore.isAuthenticated) { // 先尝试静默认证 const isAuthenticated = await authStore.checkAuth(); if (!isAuthenticated) return &#39;/login&#39;; } }); export default router; ``` #### 4. 登录组件示例 ```vue <!-- src/views/Login.vue --> <script setup lang="ts"> import { ref } from &#39;vue&#39;; import { useAuthStore } from &#39;@/stores/authStore&#39;; const authStore = useAuthStore(); const username = ref(&#39;&#39;); const password = ref(&#39;&#39;); const error = ref(&#39;&#39;); const handleLogin = async () => { try { await authStore.login({ username: username.value, password: password.value }); router.push(&#39;/profile&#39;); } catch (err) { error.value = &#39;用户名或密码错误&#39;; } }; </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(&#39;access_token&#39;, token, { httpOnly: true, // 防止XSS攻击 secure: true, // 仅HTTPS传输 sameSite: &#39;strict&#39;,// 防止CSRF攻击 path: &#39;/&#39;, 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攻击窃取令牌 - 配合SameSiteSecure属性 2. **会话过期处理**: ```typescript // 前端定期检查会话 setInterval(() => { if (authStore.isAuthenticated) { authStore.checkAuth(); } }, 300000); // 每5分钟 ``` 3. **敏感操作保护**: ```typescript // 关键操作需要二次验证 @Post(&#39;change-password&#39;) @UseGuards(JwtAuthGuard, TwoFactorGuard) async changePassword() { // ... } ``` 4. **监控与日志**: - 记录所有认证相关操作 - 监控异常登录尝试 - 实现会话设备管理 此方案结合了JWT的无状态特性Redis会话管理的灵活性,通过HttpOnly Cookie实现安全认证,适合生产环境部署[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值