How to add Okta access token by default to all axios request

31 Views Asked by At

I have setup Okta with my vuejs application. To communicate with my api you need an access token with every axios reqeust. The axios config is setup as follows:

import axios, { AxiosInstance } from 'axios';

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

// Set config defaults when creating the instance
const api = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:5293/api' : 'https://testsite.com/api',
    headers: { 'Content-type': 'application/json' },
  });
  
  // Alter defaults after instance has been created
  //instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

export default api

This works great but in order to do the request I have to manually add the header:

      const oktaAuth = getCurrentInstance()?.appContext.app.config.globalProperties.$auth as OktaAuth
  const accessToken = oktaAuth.getAccessToken();
  const config = {
    headers:{
      Authorization: 'Bearer ' + accessToken,
    }
  };

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

It is not a huge pain to add the token each time but if there is a way to do this by default in the config file that would be great. I tried taking the getInstance() and doing in the config but the token comes back as null always so I am thinking its because its not reactive and the axios config file loads before even logging in.

0

There are 0 best solutions below