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

Google Identity API:Vue+JS中无需撤销用户连接的登出方法咨询

新版Google Identity API非彻底断开的登出实现(Vue+JS)

核心逻辑

新版Google Identity API的revoke方法是彻底撤销应用对用户的授权,而你需要的普通登出仅需清除前端会话数据+重置Google登录按钮状态,无需断开应用与用户的关联。

具体实现步骤

1. 清除前端本地会话数据

先移除你存储的用户凭证、资料等信息(比如localStorage、Vuex状态):

// 清除localStorage中的用户数据
localStorage.removeItem('google_user_token');
localStorage.removeItem('google_user_profile');

// 若使用Vuex,提交重置用户状态的mutation
this.$store.commit('RESET_USER_STATE');

2. 重置Google登录按钮状态

调用GSI提供的disableAutoSelect()方法,让登录按钮回到未登录的初始状态:

if (window.google?.accounts?.id) {
  window.google.accounts.id.disableAutoSelect();
}

3. 可选:清除Google会话Cookie(强制重新选号)

如果希望用户下次打开页面时需要手动选择账号(但仍保留授权),可以清除浏览器中Google相关的会话Cookie:

// 清除Google账号选择相关Cookie
document.cookie = 'G_ENABLED_IDPS=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.google.com';
document.cookie = 'G_AUTHUSER=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.google.com';

完整Vue组件示例

<template>
  <button @click="handleLogout">登出</button>
</template>

<script>
export default {
  methods: {
    handleLogout() {
      // 清除本地用户数据
      localStorage.removeItem('google_user_token');
      localStorage.removeItem('google_user_profile');
      this.$store.commit('user/resetUser'); // 假设Vuex有对应mutation

      // 重置Google登录按钮状态
      if (window.google?.accounts?.id) {
        window.google.accounts.id.disableAutoSelect();
      }

      // 可选:清除Google会话Cookie
      document.cookie = 'G_ENABLED_IDPS=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.google.com';
      document.cookie = 'G_AUTHUSER=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.google.com';

      // 跳转至登录页或首页
      this.$router.push('/login');
    }
  }
}
</script>

关键注意点

  • 不要调用revoke方法,该操作会彻底切断应用与用户的授权关系,用户下次登录需重新授权。
  • disableAutoSelect()仅重置登录按钮的自动选择状态,用户仍可快速选择已授权的账号登录。
  • 若后端存储了用户会话,需同步调用后端接口销毁服务器端会话,确保登出彻底。

内容的提问来源于stack exchange,提问作者thebeancounter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 14:52:36