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.