How to get access token in @okta/okta-vue in Vue 3 Pinia store

We’re trying to migrate our applications to Vue 3 and are refactoring our authentication logic. In our old code, we would access the access token through something like:

const token = await this.$auth.getAccessToken();

We’re now implementing a Pinia store that needs to get the access token from okta-vue. Through some inspection in Vue DevTools, I was able to see that I can get it via:

import { useAuth } from "@okta/okta-vue";

const auth = useAuth();
const token = auth.authStateManager._authState.accessToken;

This doesn’t feel “right” to me. The underscore in the authState variable communicates that I’m referencing private state. Is there some other way to get the access token from the library?

Note that this code is not within a component, but it’s inside a Pinia store. I’m aware that within a component, I can access authState directly, but I can’t seem to find something similar within a store.

I am also very new to Okta. I have tried this which works for me.

import { defineComponent, ref, getCurrentInstance, onMounted   } from 'vue'

 setup(context, { expose }) {
   
  
    onMounted(async() => {

      const auth = getCurrentInstance().appContext.app.config.globalProperties.$auth


      const idToken = await auth.token?.parseFromUrl()
      .then(async res => {
        const { idToken } = res.tokens;
        const { accessToken } = res.tokens;

        console.log(`Hi ${idToken.claims.email}!`);
        console.log(`accessToken ${accessToken}!`);
      
        }
      })
    })
    expose({ onAuthRequired });
    return {onAuthRequired}
  },

I’m not within the context of a component. I’m trying to get the access token within a Pinia store, specifically.

I don’t know anything about Pinia store but there must be some Pinia plugin or something that allows you access to context. Good luck!

One of my colleagues discovered we can use:

const token = auth.authStateManager.getAuthState().accessToken;

This at least removes the access to the private _authState variable. If anyone knows of another way we’re “supposed to” access the accessToken, I’m open to alternatives.

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