I have an Ionic app that needs to authenticate in Azure, so I installed MSAL following this tutorial: https://learn.microsoft.com/en-us/graph/tutorials/angular
It works like a charm with "ionic serve" but when I run it in the device, it crashes when I try to sign in Azure. I think it is because the popup window MSAL shows for login is not allowed in Ionic.
So my first attempt was to change the loginPopup() call for a loginRedirect(). So I removed this code:
async signIn(): Promise<void> {
const result = await this.msalService
.loginPopup(OAuthSettings)
.toPromise()
.catch((reason) => {
this.alertsService.addError('Login failed',
JSON.stringify(reason, null, 2));
});
if (result) {
this.msalService.instance.setActiveAccount(result.account);
this.authenticated = true;
this.user = await this.getUser();
}
}
And I added this new one (based on https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/errors.md):
async signIn(): Promise<void> {
await this.msalService.instance.handleRedirectPromise();
const accounts = this.msalService.instance.getAllAccounts();
if (accounts.length === 0) {
// No user signed in
this.msalService.instance.loginRedirect();
}
}
But this way, the user information is not saved, because I have not a "result" to handle or to call to setActiveAccount(result). It did not work even in "ionic serve", so I discarded this approach.
The second approach, after seaching for a posible solution for two days, was to show the popup in a InAppBrowser (https://ionicframework.com/docs/native/in-app-browser), so I changed the code to:
async signIn(): Promise<void> {
const browser = this.iab.create('https://www.microsoft.com/');
browser.executeScript({ code: "\
const result = await this.msalService\
.loginPopup(OAuthSettings)\
.toPromise()\
.catch((reason) => {\
this.alertsService.addError('Login failed',\
JSON.stringify(reason, null, 2));\
});\
if (result) {\
this.msalService.instance.setActiveAccount(result.account);\
this.authenticated = true;\
this.user = await this.getUser();\
}"
});
}
But it just open a new window and do nothing more, it does not execute loginPopup(), so I also discard this second approach.
Anyone knows how to avoid the popup problem in Ionic?
Thank you