【Vue3+TypeScript】H5项目实现企业微信OAuth2.0授权登录完整指南

发布于:2025-09-07 ⋅ 阅读:(21) ⋅ 点赞:(0)

【Vue3+TypeScript】H5项目实现企业微信OAuth2.0授权登录完整指南

企业微信OAuth2.0授权登录是企业内部应用常见的功能需求,本文将详细介绍如何在Vue3+TypeScript项目中实现企业微信OAuth2.0授权登录功能。

企业微信OAuth2.0授权流程概述

根据企业微信官方文档,OAuth2.0授权登录主要包含以下步骤:

  1. 前端引导用户到企业微信授权页面
  2. 用户同意授权后,企业微信重定向回应用并附带code
  3. 前端将code发送到后端服务器
  4. 后端使用code换取access_token和用户信息
  5. 前端接收登录结果并更新应用状态

核心代码实现

import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import NProgress from "@/utils/nprogress";
import router from "@/router";
import { usePermissionStore, useUserStore } from "@/store";
import WEWORK_CONFIG from "@/config/weworkConfig";

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login"];
  const authUrl = WEWORK_CONFIG.AUTH_URL;
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const access_token = localStorage.getItem("access_token");
    if (
      access_token &&
      access_token !== "undefined" &&
      access_token !== null &&
      access_token !== "" &&
      access_token !== "null"
    ) {
      // 判断是否登录

      if (to.path === "/login") {
        // 已登录,访问登录页,跳转到首页
        next({ path: "/" });
      } else {
        const permissionStore = usePermissionStore();
        // 判断路由是否加载完成
        if (permissionStore.isRoutesLoaded) {
          if (to.matched.length === 0) {
            // 路由未匹配,跳转到404
            next("/404");
          } else {
            // 动态设置页面标题
            const title = (to.params.title as string) || (to.query.title as string);
            if (title) {
              to.meta.title = title;
            }
            next();
          }
        } else {
          try {
            // 加载路由
            const dynamicRoutes = await permissionStore.generateRoutes();
            dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
            next({ ...to, replace: true });
            console.log("静态路由:", dynamicRoutes);
          } catch (error) {
            console.error(error);
            // 路由加载失败,重置 token 并重定向到登录页
            await useUserStore().clearUserData();
            redirectToLogin(to, next);
            NProgress.done();
          }
        }
      }
    } else {
      // 未登录,判断是否在白名单中
      if (whiteList.includes(to.path)) {
        next();
      } else {
        //不在白名单中,检测用户是否授权(code),若无授权跳转到授权页面,有授权则获取token
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get("code");

        if (code) {
        //请求后台接口,使用code换取access_token和用户信息
          useUserStore()
            .LoginWeiXin({
              code: code,
            })
            .then(() => {
              next();
            })
            .catch((err) => {
              // 登录失败,清空缓存,重定向至构造网页授权链接
              console.error(`登录报错:${err}。code:${code}`);
              
              useUserStore()
                .clearUserData()
                .then(() => {
                  redirectToLogin(to, next);
                });
            });

          const permissionStore = usePermissionStore();
          try {
            // 加载路由
            const dynamicRoutes = await permissionStore.generateRoutes();
            dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
            next();
            console.log("静态路由:", dynamicRoutes);
          } catch (error) {
            console.error(error);
            // 路由加载失败,重置 token 并重定向到登录页
            await useUserStore().clearUserData();
            redirectToLogin(to, next);
            NProgress.done();
          }
        } else {
          //未授权
          window.location.href = authUrl;
          NProgress.done();
        }
      }
    }
  });

  // 后置守卫,保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done();
  });
}

// 重定向到登录页
function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
  localStorage.clear();
  const authUrl = WEWORK_CONFIG.AUTH_URL;
  window.location.href = authUrl;
}

总结

本文详细介绍了在Vue3+TypeScript项目中实现企业微信OAuth2.0授权登录的完整流程,包括:

  1. 企业微信授权流程的理解
  2. 工具类的封装
  3. 状态管理
  4. API接口设计
  5. 登录页面实现
  6. 路由守卫配置
  7. 环境变量和部署注意事项

通过以上实现,你可以为企业内部应用添加安全可靠的企业微信登录功能,提升用户体验和安全性。实际项目中还需根据具体需求进行调整和优化。

希望这篇博客对你有所帮助,欢迎留言交流!


网站公告

今日签到

点亮在社区的每一天
去签到