Home » vue » How do I re-acquire a token from AAD using vue-msal after I close the browser tab and open the page again?

How do I re-acquire a token from AAD using vue-msal after I close the browser tab and open the page again?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have the following code for a Vue JS based single page application connecting to Azure AD via vue-msal which works when I:

  • open up the web app for the very first time
    • takes me to the AAD login page
    • once logged in, redirects me back to my app
  • I can then do a console.log() and print out my access token etc to verify login was successful and token was acquired successfully

Now suppose I close the browser tab. My login session is still there (after all, I haven’t deleted any cookies!) but now my access token is gone (presumably because it was saved as a variable rather than in a cookie). How do I re-acquire the access token when I open up a new tab and navigate to my application?

# main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import msal from 'vue-msal';

Vue.config.productionTip = false

Vue.use(msal, {
  auth: {
    clientId: "CLIENT_ID_OF_MY_SINGLE_PAGE_APPLICATION"
    authority: "https://login.microsoftonline.com/TENANT_ID/",
    redirectUri: "http://localhost:8080/",
    requireAuthOnInitialize: true
  },
  request: {
    scopes: [ `user.read`, `https://backend-api-hosted-on-functionapp.azurewebsites.net/user_impersonation` ]
  },
  graph: {
    callAfterInit: true,
  },
  cache: {
    cacheLocation: "sessionStorage"
  }
});

new Vue({
  router,
  render: h => h(App),
  data: function() {
    return {
      dummyVariable: 'dummyValue',
    }
  },
  created() {
    console.log("User auth status is: " + this.$msal.isAuthenticated());
    console.log("User data object: " + JSON.stringify(this.$msal)) // shows the bearer token the first time, but when I then close the tab and re-open the tab, I see nothing here
  }

}}).$mount('#app')

So I have a few questions:

  1. Am I "meant to be" re-acquiring a new token if the application is loaded up again? Is this conventional practice?

  2. If so, how do I go about doing it? I tried using using:

    if ((this.$msal.data.isAuthenticated == false) || (this.$msal.data.accessToken == false)) {
      console.log("New token required");
      this.$msal.signIn();
      console.log("User data object: " + JSON.stringify(this.$msal))
    }

But that doesn’t give me anything back unfortunately.

Answers:

On the off chance anyone else ends up looking at this question, this isn’t an issue with my code as such, but an ongoing issue between vue-msal and the msal packages, as explained in this GH issue: https://github.com/mvertopoulos/vue-msal/issues/33