I’m using auth0-spa-js for getting a token via the auth code flow. However it seems that when I call auth0.isAuthenticated(), it always returns false. This leads to restarting the auth code flow if it is not the initial redirect from the auth server.
Here is the code that gets called on each page reload:
import createAuth0Client from '@auth0/auth0-spa-js'
import axios from 'axios'
export default async ({ app, router, Vue }) => {
let auth0 = await createAuth0Client({
domain: '{domain}.auth0.com',
client_id: '{client_id}',
audience: '{audience}'
});
const isAuthenticated = await auth0.isAuthenticated()
if (isAuthenticated) {
// show the gated content
await afterLogin(auth0, Vue)
return
}
const query = window.location.search
if (query.includes("code=") && query.includes("state=")) {
// Process the login state
await auth0.handleRedirectCallback()
await afterLogin(auth0, Vue)
// Use replaceState to redirect the user away and remove the querystring parameters
window.history.replaceState({}, document.title, "/")
return
}
await auth0.loginWithRedirect({
redirect_uri: window.location.origin
});
}
async function afterLogin(auth0, Vue) {
let user = await auth0.getUser()
Vue.prototype.$user = user
Vue.prototype.$auth = auth0
// let claims = await auth0.getIdTokenClaims()
// console.log(claims)
// setAuthHeader(claims.__raw)
let token = await auth0.getTokenSilently()
setAuthHeader(token)
}
function setAuthHeader(token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token
}