You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt中设置localStorage授权令牌随浏览器会话结束失效

解决方案

核心问题是localStorage本身是持久化存储,不会随浏览器会话结束自动清除,要实现未勾选「记住我」时会话结束登出,得改用sessionStorage存储令牌(会话级存储,关闭浏览器即清除),同时配合会话级Cookie。具体操作如下:

1. 登录时传递「记住我」参数

在登录表单提交时,将「记住我」复选框的状态(true/false)作为参数传给登录接口,比如在请求体中添加rememberMe字段。

2. 修改自定义认证策略(customScheme)

在~/schemes/customScheme.js中重写login方法,根据rememberMe的值决定令牌存储方式:

async login(endpoint, { rememberMe, ...data }) {
  // 发送登录请求获取令牌
  const response = await this.$auth.request(endpoint, data)
  const token = response.data[this.options.tokenName]

  if (rememberMe) {
    // 勾选记住我:使用localStorage持久化存储,同时设置Cookie有效期(示例:7天)
    this.$auth.storage.setLocalStorage(this.options.tokenName, token)
    this.$auth.storage.setCookie(this.options.tokenName, token, { expires: 7 })
  } else {
    // 未勾选:使用sessionStorage会话级存储,Cookie保持会话级(默认不设置expires)
    this.$auth.storage.setSessionStorage(this.options.tokenName, token)
    this.$auth.storage.setCookie(this.options.tokenName, token)
  }

  // 设置当前用户令牌
  this.$auth.setUserToken(token)
  return response
}

3. 自定义登出逻辑(清除对应存储)

因为配置中logout: false,需要在自定义scheme中添加logout方法,确保清除所有存储的令牌:

async logout() {
  // 清除localStorage、sessionStorage和Cookie中的令牌
  this.$auth.storage.removeLocalStorage(this.options.tokenName)
  this.$auth.storage.removeSessionStorage(this.options.tokenName)
  this.$auth.storage.removeCookie(this.options.tokenName)
  // 重置认证状态
  this.$auth.reset()
}

4. 调整auth配置文件

移除endpoints下的localStorage配置项,让自定义scheme完全控制存储逻辑:

export default {
  watchLoggedIn: true,
  strategies: {
    local: false,
    customStrategy: {
      _scheme: '~/schemes/customScheme',
      endpoints: {
        login: {
          url: '/v2/dashboard/auth/login',
          method: 'post',
        },
        logout: false,
        cookie: {
          prefix: '',
        },
        token: {
          prefix: '',
        },
      },
      tokenName: 'sp-api-key',
      tokenRequired: true,
      globalToken: true,
      tokenType: '',
    },
  }
}

说明:sessionStorage的生命周期与浏览器会话绑定,关闭浏览器窗口/标签页后会自动清除存储的令牌,配合会话级Cookie,就能实现未勾选「记住我」时自动登出的需求。

内容的提问来源于stack exchange,提问作者Алексей Марков

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:52:57