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

如何为所有Axios请求默认添加Okta访问令牌

解决方案:用Axios请求拦截器自动添加Okta访问令牌

你遇到的问题核心是Axios实例初始化时机早于用户登录,且getCurrentInstance()仅能在Vue组件上下文内使用,所以直接在配置文件中设置令牌头不可行。正确的做法是利用Axios请求拦截器,它会在每次请求发起时执行,此时用户已完成登录,能正常获取到访问令牌。

步骤1:确保OktaAuth实例可全局访问

首先,将OktaAuth实例单独导出(比如创建okta.js文件),方便Axios配置文件导入:

// src/okta.js
import { OktaAuth } from '@okta/okta-auth-js';

const oktaAuth = new OktaAuth({
  issuer: 'https://你的Okta域名/oauth2/default',
  clientId: '你的客户端ID',
  redirectUri: `${window.location.origin}/login/callback`,
  // 其他Okta配置项
});

export default oktaAuth;

在main.js中挂载到Vue全局(保留原有操作即可):

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import oktaAuth from './okta';

const app = createApp(App);
app.config.globalProperties.$auth = oktaAuth;
// 其他挂载操作(如路由、Axios)
app.mount('#app');

步骤2:修改Axios配置,添加请求拦截器

在你的Axios配置文件中,导入OktaAuth实例并添加请求拦截器,每次请求前自动注入令牌:

import axios, { AxiosInstance } from 'axios';
import oktaAuth from './okta'; // 导入OktaAuth实例

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

const api = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:5293/api' : 'https://testsite.com/api',
  headers: { 'Content-type': 'application/json' },
});

// 请求拦截器:自动添加Authorization头
api.interceptors.request.use(
  async (config) => {
    // 先检查用户是否已认证
    if (await oktaAuth.isAuthenticated()) {
      // 获取访问令牌(Okta会自动刷新过期令牌)
      const accessToken = await oktaAuth.getAccessToken();
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

export default api;

步骤3:简化API调用代码

现在所有Axios请求都会自动携带令牌头,无需手动配置headers:

function getAppointmentData() {
  api.get<appointmentList[]>('/calendar')
    .then((response) => {   
      dataAppointmentList.value = response.data;   
    })
    .catch(() => {
      dataAppointmentList.value = []; 
      console.log('API request failed');
    })
}

关键说明

  • 拦截器会在每次请求发起前执行,此时用户已完成登录,能有效获取令牌;
  • 使用await oktaAuth.isAuthenticated()和await oktaAuth.getAccessToken()是为了处理令牌过期的情况,Okta会自动刷新即将过期的令牌;
  • 避免在非组件上下文使用getCurrentInstance(),它仅适用于Vue组件的setup函数或生命周期钩子中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:38:15