Azure B2C - PublicClientApplicatcion.AcquireTokenByUsernamePasswordAsync fails

Viewed 520

I have trouble to sign in to my Azure B2C Active Directory with username and password from .net core console app. I am using the MSAL Library 2.6 from nuget. I found this example on GitHub https://github.com/Azure-Samples/active-directory-dotnetcore-console-up-v2

I reduced the code to a minimum it looks like this:

public static async Task TestLogin()
{
    try
    {
        var scopes = new[] { "community.member" };
        var username = "{user@domain.com}";
        var password = new SecureString();

        foreach (var c in "{Password}")
        {
            password.AppendChar(c);
        }

        var app = new PublicClientApplication("{B2C Application ID}", "https://{Application Name}.b2clogin.com/tfp/xxxxxxx-xxxx-xxxxxxxxxxxx/B2C_1_NativeSigneIn");

        var result = await app.AcquireTokenByUsernamePasswordAsync(scopes, username, password);
        Console.WriteLine($"Token: {result.AccessToken}");
    }
    catch (MsalServiceException ex)
    {
        Console.WriteLine($"{ex.Message} - {ex.ErrorCode}");
    }
}

I am always getting the following MSAL exception: Message: User realm discovery failed ErrorCode: user_realm_discovery_failed

2 Answers

The old library has a bug in it. The new version of MSAL has the fix. You can read about the issue and the resolution here:

https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/926

Basically you need to download the local version of the package that one of the developers compiled from the GITHUB source, reference that package from your solution by pointing NuGet Package Manager to the downloaded package, then you need to rework the API for the new Fluent API for MSAL, and it'll work! Easy as that.

I tried the B2C policy, the ropc flow cannot support other policies, you could only use the ropc policy.

enter image description here

For the details, you could read here.

Related