azureazure-ad-msal

Can't find Assembly for GetConsoleOrTerminalWindow


I'm trying to implement an MSAL Interactive scenario login in a desktop Windows application. The sample code includes .WithParentActivityOrWindow(GetConsoleOrTerminalWindow) when building the Public Client Application.

I don't have GetConsoleOrTerminalWindow available to me and I can't find the package or assembly to reference to access it. It's obviously an IntPtr handle to the relevant window, but it just says it's not declared.

Am I missing something obvious?


Solution

  • The sample code that you are referring from this MS Document uses authentication broker component like Web Account Manager(WAM) for public client scenarios.

    In my case, I registered one application and added below redirect URI in Mobile & Desktop applications platform, along with enabling public client flows option:

    ms-appx-web://microsoft.aad.brokerplugin/appIdhere
    

    enter image description here

    Now, I created one .NET 6.0 console app and installed Microsoft.Identity.Client & Microsoft.Identity.Client.Broker packages in it like this:

    enter image description here

    To generate access token using interactive flow in this application, I used below sample code in it:

    Program.cs:

    using System.Runtime.InteropServices;
    using Microsoft.Identity.Client;
    using Microsoft.Identity.Client.Broker;
    
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr GetConsoleWindow();
    
        static async Task Main(string[] args)
        {
            var scopes = new[] { "User.Read" };
            var tenantId = "yourtenantIDhere";
            var authority = $"https://login.microsoftonline.com/{tenantId}";
    
            var brokerOptions = new BrokerOptions(BrokerOptions.OperatingSystems.Windows)
            {
                Title = "My Awesome Application"
            };
    
            IPublicClientApplication app = PublicClientApplicationBuilder.Create("yourappIDhere")
                .WithDefaultRedirectUri()
                .WithAuthority(authority)
                .WithParentActivityOrWindow(() => GetConsoleWindow())
                .WithBroker(brokerOptions)
                .Build();
    
            AuthenticationResult result = null;
    
            try
            {
                IEnumerable<IAccount> accounts = await app.GetAccountsAsync();
                IAccount existingAccount = accounts.FirstOrDefault();
    
                if (existingAccount != null)
                {
                    result = await app.AcquireTokenSilent(scopes, existingAccount).ExecuteAsync();
                }
                else
                {
                    Console.WriteLine("No accounts found in the cache.");
                }
    
                if (result == null)
                {
                    Console.WriteLine("Acquiring token interactively...");
                    result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
                }
            }
            catch (MsalUiRequiredException ex)
            {
                result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                return;
            }
    
            if (result != null)
            {
                Console.WriteLine("Access Token:");
                Console.WriteLine(result.AccessToken);
            }
            else
            {
                Console.WriteLine("Failed to acquire token.");
            }
        }
    }
    

    Response:

    enter image description here

    Access token:

    enter image description here

    When I decoded the above access token in jwt.ms, I got aud and scp claim values like this:

    enter image description here