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
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!
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.
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.