How to get access token in my axios global config file - Vue 3

Hello, hope you’re all well :slight_smile:

I’m trying to avoid manually calling the getAccessTokenSilently() line everytime I want to call my API and just use the Axios global defaults. I’ve created an axios.js file in my application that contains the following:

//Import Axios Library and Auth0
import axios from 'axios';
import { useAuth0 } from "@auth0/auth0-vue"

//Create instance of axios
const instance = axios.create({
    baseURL: 'http://localhost:5000/api/v1'
});

// Create a request interceptor for my instance and get accessToken on the fly
instance.interceptors.request.use(async (config) => {
    const { getAccessTokenSilently } = useAuth0();
    const accessToken = await getAccessTokenSilently();
    config.headers['Authorization'] = accessToken;
    return config;
}, (error) => {
    return Promise.reject(error)
});

export default instance;

Basically I’m trying to attach the accessToken using the request interceptor function but it won’t work and the authorization header doesn’t get added. Is this the correct way to do so? If not, can you please let me know best practices (if available).

I couldn’t find a proper method to retrieve an accessToken outside a component file in auth0 docs using the vue-sdk file.

I’m fairly new to this so any help is greatly appreciated :slight_smile:

EDIT:

Just on how I make my API calls, I’m using Pinia actions to invoke API requests by importing the axios config file and call the API endpoint. See the following pinia store code:

//Import the Pinia Library
import { defineStore } from 'pinia'
//Import the Axios Library for API calls
import axiosConfig from "@/config/axios.js"

export const useUserStore = defineStore('user', {
  state: () => ({
    user:{}
  }),
  getters: {
    getUser(state){
      return state.user
    }
  },
  actions: {
    async fetchUser(){
      try {
        const data = await axiosConfig.get('/profile')
        this.user = data.data
      } catch (error) {
        console.log("User Pinia error: " + error)
      }
    }
  },
})

Please let me know if you require more information!

1 Like

Hi All,

Just following up on this as it’s been a week. Would I be able to get an answer sooner rather than later?

Thanks

This is for Vue 3 (3.x) and @auth0/auth0-vue (2.x.beta). I have the luxury of a future release date so I can wait for the official @auth0/auth0-vue 2.x release. Please note, this works for me and may not be the best solution.

You can’t call getAccessTokenSilently() outside of a component or setup. This becomes a problem when you group your api calls into different api service files.

I register application level functionality using a simple Vue 3 plugin pattern.

src/plugins/auth.ts

import { createAuth0 } from '@auth0/auth0-vue'
import type { Auth0Plugin } from '@auth0/auth0-vue'
import authConfig from '../../auth_config.json'

const client: Auth0Plugin = createAuth0({
  domain: authConfig.domain,
  clientId: authConfig.clientId,
  authorizationParams: {
    redirect_uri: window.location.origin,
    audience: authConfig.audience,
    scope: 'openid profile email'
  }
})

export default client

export const getAccessToken = async () => {
  const accessToken = await client.getAccessTokenSilently()
  return accessToken
}

Incomplete src/services/api.ts below, just showing the request interceptor.

import { getAccessToken } from '@/plugins/auth'

instance.interceptors.request.use(
  async (config) => {
    const accessToken = await getAccessToken()
    config.headers['Authorization'] = `Bearer ${accessToken}`
    return config
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error)
  }
)

This seems to work for me. For testing, I hacked the following to force token renewal without having the user manually login.

I set the Auth0 Application.

  • ID TOken Expiration: 120 seconds
  • Refresh Token Rotation: ON
  • Reuse Interval: 60 seconds
  • Inactivity Expiration: 180 seconds.

And the Auth0 API.

  • Token Expiration: 140 seconds
  • Token Expiration For Browser Flows: 120 seconds

Tested this over a period of 15 minutes and I left a session running overnight and the code retrieved a new token silently. I’m happy with the performance.

1 Like

Hi @dak2009,

Thanks for sharing your solution with the rest of the Community!

I’m sure other community members will find this helpful!

Feel free to reach out if you have any more questions.

Thanks,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.