vue auth2实现
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-vue 或 vue-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 管理及路由保护。






