Azure-Samples / ms-identity-javascript-v2

VanillaJS sample using MSAL.js v2.x and OAuth 2.0 Authorization Code Flow with PKCE on Microsoft identity platform
MIT License
105 stars 84 forks source link

No authentication after redirect #5

Closed DarkLite1 closed 4 years ago

DarkLite1 commented 4 years ago

When using msal 1.3.0 there was no need to use the handleRedirectCallback() method. The same is true for "@azure/msal-browser": "^2.0.0-beta.2" but they handle things differently. In the new version authentication after a redirect does not happen automatically unless the page is refreshed a second time after the user authenticated on the Microsoft sign on page.

I have created a repo with the original code used by msal 1.3.0 in the master branch without issues and the new code used by msal 2 in the test-msal-2 branch that needs an extra refresh after the user is navigated back to the SPA to see that he is authenticated.

When I enable the code for authRedirectCallBack(), which comes with the sample code, it keeps looping and refreshing the page all the time.

Thank you for having a look at what I did wrong or if this is an msal code issue.

DarkLite1 commented 4 years ago

Fixed this one by adding the msal.HandleRedirectPromise as described here:

// Register Callbacks for Redirect flow
myMSALObj.handleRedirectPromise().then((tokenResponse) => {
    const accountObj = tokenResponse ? tokenResponse.account : myMSALObj.getAccount();
    if (accountObj) {
        // Account object was retrieved, continue with app progress
        console.log('id_token acquired at: ' + new Date().toString());
    } else if (tokenResponse && tokenResponse.tokenType === "Bearer") {
        // No account object available, but access token was retrieved
        console.log('access_token acquired at: ' + new Date().toString());
    } else if (tokenResponse === null) {
        // tokenResponse was null, attempt sign in or enter unauthenticated state for app
        signIn();
    } else {
        console.log("tokenResponse was not null but did not have any tokens: " + tokenResponse);
    }
}).catch((error) => {
    console.log(error);
});

For my use case:

const accountID = ref('')

export const setAccountID = () => {
  const account = auth.getAccount()

  if (account) {
    accountID.value = account.idTokenClaims.oid
  } else {
    accountID.value = ''
  }
}

auth
  .handleRedirectPromise()
  .then(setAccountID)
  .catch((error) => {
    console.log('login with redirect failed: ', error)
  })