Azure-Samples / active-directory-b2c-dotnet-desktop

Sample showing how a Windows desktop .NET (WPF) application can sign in a user using Azure AD B2C, get an access token using MSAL.NET and call an API.
http://aka.ms/aadb2c
MIT License
78 stars 38 forks source link

MsalClientException not thrown when login page is closed #77

Open ppapageo opened 3 years ago

ppapageo commented 3 years ago

I am using the following code:

try
{
    authResult = await app.AcquireTokenInteractive(App.ApiScopes)
                        .WithUseEmbeddedWebView(false)
                        .WithParentActivityOrWindow(new WindowInteropHelper(this).Handle)
                        .ExecuteAsync();
}
catch (MsalClientException ex)
{
    msg = $"Error Acquiring Token: {ex}";
}

I want to handle the case where the user is prompted to the login page, but then closes it or navigates away. For this I have observed two conflicting behaviours being documented.

On the one hand it is stated on the following wiki that MSAL will throw a MsalClientException with the error code authentication_canceled , if when calling AcquireTokenInteractive(), the user closes the process or hits the back button on their browser. https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/exceptions#common-exceptions

On the other hand on azure documentation it is stated that MSAL.NET cannot detect if the user closes the login page or navigates away. https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-web-browsers#system-browser-experience-on-net

I have confirmed that my code exhibits the later behaviour, so no exception is thrown. If that is the case and MSAL.NET cannot detect such browser behaviour, then is there a valid scenario, where the login page is closed and the program throws a MsalClientException?

jmprieur commented 3 years ago

@ppgpn : this is a valid scenario, but MSAL.NET is not notified. @bgavrilMS to keep me honest

bgavrilMS commented 3 years ago

Yes, if you use an embedded browser, then MSAL knows if the end-user closes it. If you use a system browser, this is just process to process communication, i.e. MSAL kick starts it via "open https://login.microsoft.com/stuff" and waits for the user to complete authentication. There is no way for MSAL to know if the user navigates away or closes the window.

We've added support for embedded browser on .NET Core as well, maybe you want to use that? https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/WebView2

ppapageo commented 3 years ago

Thank you for the responses,

I was assuming that B2C would send an error as a response, as it does with other behaviours happening on the system browser login, (e.g. the forgot password error code). I use the CancellationToken so that, at some point, I will get a timeout.

Unfortunately I cannot use the embedded browser because I need social logins which afaik need to be performed on the system browser.