However, I’m unable to access this.$auth in main.js of the Vue app. I’ve successfully logged in with Auth0 and in the app I can access all $auth.user in the template (*.vue files). The this.$auth in Navbar.vue script can be accessed with no problem at all for calling the this.$auth.logout function. The same also work for App.vue.
What I actually need is to get the access token with this.$auth.getTokenSilently(). Which is needed to call an Auth0 protected API throughout the app especially in my store files (vuex).
From the tutorial I know that the plugin should make the $auth & this.$auth to be available throughout the Vue app. But somehow I’m unable to access in in main.js. It always return null. Am I missing some things? I’m still a Vue noob by the way.
It seems that this.$auth is not updated without refresh of the page (login and callback was at the page home). I manage to add the login info into vuex store in another page, callback & redirect to home with success. Is this a clean solution? Or is there a better way to do it? TIA
Dealing with the same issue here, I want to pass accessToken from getTokenSilently() to apolloClient, but unable to do so. For the moment I’m using localStorage to store accessToken, but I believe there is a better solution. Maybe @steve.hobbs can help us out?
@faizalec As you’ve discovered, this.$auth won’t be available inside main.js as it only get applied to Vue components.
However, the wrapper supplied with the sample exports a getInstance function that you can use to get access to the same thing. You do need to be a bit careful, as methods like getTokenSilently (which comes from the SPA JS SDK) only work once the SDK has been completely initialized. i.e., when loading is false. So you need to set up a $watch on this to make sure you can access the token at the right time (assuming you’re logged in).
Something like this snippet should work. Place it inside main.js, with the import at the top (amending what you might already have) and the $watch code after the Vue.use(Auth0Plugin...) call:
// Import getInstance from the auth wrapper
import { Auth0Plugin, getInstance } from './auth';
// ...
const instance = getInstance();
instance.$watch("loading", async loading => {
if (!loading && instance.isAuthenticated) {
const token = await instance.getTokenSilently();
console.log(token);
}
});