Skip to content

Device Code Flow

Mark Zuber edited this page Sep 28, 2018 · 34 revisions

Note: this feature is not yet available in the public release of MSAL

How to use it?

PublicClientApplicationcontains the method AcquireTokenWithDeviceCodeAsync

The following sample presents the most current case, with explanations of the kind of exceptions you can get, and their mitigations

static async Task GetATokenForGraph()
{
    // This code should be in your application startup / main function.
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    // 

    string authority = "https://login.microsoftonline.com/contoso.com";
    string[] scopes = new string[] { "user.read" };
    PublicClientApplication app = new PublicClientApplication(clientId, authority);

    try
    {
        AuthenticationResult result = await app.AcquireTokenWithDeviceCodeAsync(scopes, deviceCodeCallback =>
            {
                // This will print the message on the console which tells the user where to go sign-in using 
                // a separate browser and the code to enter once they sign in.
                // The AcquireTokenWithDeviceCodeAsync() method will poll the server after firing this
                // device code callback to look for the successful login of the user via that browser.
                // This background polling (whose interval and timeout data is also provided as fields in the 
                // deviceCodeCallback class) will occur until:
                // * The user has successfully logged in via browser and entered the proper code
                // * The timeout specified by the server for the lifetime of this code (typically ~15 minutes) has been reached
                // * The developing application calls the Cancel() method on a CancellationToken sent into the method.
                //   If this occurs, an OperationCanceledException will be thrown (see catch below for more details).
                Console.WriteLine(deviceCodeCallback.Message);
            },
            CancellationToken.None);

        Console.WriteLine(result.Account.Username);
    }
    catch (MsalServiceException ex)
    {
        // Kind of errors you could have (in ex.Message)

        // MsalServiceException: AADSTS90010: The grant type is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint.
        // you used common.
        // Mitigation: as explained in the message from Azure AD, the authoriy needs to be tenanted or otherwise organizations
    }
    catch (OperationCanceledException ex)
    {
        // If you use a CancellationToken, and call the Cancel() method on it, then this may be triggered
        // to indicate that the operation was cancelled. 
        // See https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads 
        // for more detailed information on how C# supports cancellation in managed threads.
    }    
}

Getting started with MSAL.NET

Acquiring tokens

Web Apps / Web APIs / daemon apps

Desktop/Mobile apps

Advanced topics

FAQ

Other resources

Clone this wiki locally