当前位置:首页 > VUE

vue auth2实现

2026-01-21 20:05:32VUE

Vue 中实现 OAuth2 认证

安装依赖

使用 vue-auth@okta/okta-vue 等库简化流程。若需手动实现,安装基础依赖:

npm install axios vue-router vuex

配置 OAuth2 客户端

在 Vue 项目根目录创建 .env 文件存储认证服务商提供的配置:

VUE_APP_OAUTH2_CLIENT_ID=your_client_id
VUE_APP_OAUTH2_AUTH_ENDPOINT=https://provider.com/auth
VUE_APP_OAUTH2_TOKEN_ENDPOINT=https://provider.com/token
VUE_APP_OAUTH2_REDIRECT_URI=http://localhost:8080/callback

实现登录跳转

创建登录按钮,点击时跳转至 OAuth2 服务商的授权页面:

// AuthService.js
import axios from 'axios';

export const redirectToAuthServer = () => {
  const params = new URLSearchParams({
    response_type: 'code',
    client_id: process.env.VUE_APP_OAUTH2_CLIENT_ID,
    redirect_uri: process.env.VUE_APP_OAUTH2_REDIRECT_URI,
    scope: 'openid profile email',
  });
  window.location.href = `${process.env.VUE_APP_OAUTH2_AUTH_ENDPOINT}?${params}`;
};

处理回调并获取 Token

在路由配置中定义回调路由,解析授权码并交换 Token:

// router/index.js
import { exchangeCodeForToken } from '@/services/AuthService';

const router = new VueRouter({
  routes: [
    {
      path: '/callback',
      beforeEnter: async (to, from, next) => {
        try {
          const { code } = to.query;
          const token = await exchangeCodeForToken(code);
          store.commit('setAuth', token); // 存储 Token
          next('/dashboard');
        } catch (error) {
          next('/login');
        }
      },
    },
  ],
});

// AuthService.js
export const exchangeCodeForToken = async (code) => {
  const response = await axios.post(
    process.env.VUE_APP_OAUTH2_TOKEN_ENDPOINT,
    new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: process.env.VUE_APP_OAUTH2_REDIRECT_URI,
      client_id: process.env.VUE_APP_OAUTH2_CLIENT_ID,
    }),
    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  );
  return response.data.access_token;
};

存储和验证 Token

使用 Vuex 管理 Token 状态,并通过 Axios 拦截器附加 Token 到请求头:

// store/index.js
export default new Vuex.Store({
  state: { token: null },
  mutations: {
    setAuth(state, token) {
      state.token = token;
      localStorage.setItem('token', token);
    },
  },
});

// main.js
axios.interceptors.request.use((config) => {
  const token = store.state.token || localStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

路由守卫保护页面

通过全局路由守卫检查认证状态:

// router/index.js
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.token || localStorage.getItem('token');
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

刷新 Token 处理

若 Token 过期,使用 Refresh Token 获取新 Token(需 OAuth2 服务商支持):

// AuthService.js
export const refreshToken = async () => {
  const response = await axios.post(
    process.env.VUE_APP_OAUTH2_TOKEN_ENDPOINT,
    new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: localStorage.getItem('refresh_token'),
      client_id: process.env.VUE_APP_OAUTH2_CLIENT_ID,
    })
  );
  store.commit('setAuth', response.data.access_token);
};

第三方库简化流程

推荐使用 @okta/okta-vuevue-auth0 等封装库,例如 Okta 集成示例:

// main.js
import OktaVue from '@okta/okta-vue';

Vue.use(OktaVue, {
  issuer: 'https://your-okta-domain.com/oauth2/default',
  client_id: 'your_client_id',
  redirect_uri: window.location.origin + '/callback',
  scopes: ['openid', 'profile', 'email'],
});

通过以上步骤,Vue 应用可完整实现 OAuth2 认证流程,包括登录、回调处理、Token 管理及路由保护。

vue auth2实现

标签: vue
分享给朋友:

相关文章

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{ 'b…

vue实现报表

vue实现报表

vue实现报表的方法 使用Vue实现报表通常需要结合图表库或表格组件。以下是几种常见方法: 使用ECharts 安装ECharts库: npm install echarts vue-echart…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…