Skip to content

A .NET Core console application which gets an access token to call Microsoft Graph using a username and password

License

Notifications You must be signed in to change notification settings

Azure-Samples/active-directory-dotnetcore-console-up-v2

Repository files navigation

page_type languages products description urlFragment
sample
csharp
powershell
microsoft-entra-id
This sample demonstrates how to use MSAL.NET to authenticate the user silently using username and password and call to a web API (in this case, the Microsoft Graph)
Microsoft Entra ID-username-password-graph

.NET Core Console application letting users sign-in with Username/password to call Microsoft Graph API

Build status

We have renamed the default branch to main. To rename your local repo follow the directions here.

About this sample

Overview

This sample demonstrates how to use MSAL.NET to:

  • authenticate the user silently using username and password.
  • and call to a web API (in this case, the Microsoft Graph)

Topology

If you would like to get started immediately, skip this section and jump to How To Run The Sample.

Scenario

The application obtains a token through username and password, and then calls the Microsoft Graph to get information about the signed-in user and their manager.

Note that Username/Password is needed in some cases (for instance DevOps scenarios) but it's not recommended because:

  • This requires having credentials in the application, which does not happen with the other flows.
  • The credentials should only be used when there is a high degree of trust between the resource owner and the client and when other authorization grant types are not available (such as an authorization code).
  • Do note that this attempts to authenticate and obtain tokens for users using this flow will often fail with applications registered with Microsoft Entra ID. Some of the situations and scenarios that will cause the failure are listed below
    • When the user needs to consent to permissions that this application is requesting.
    • When a conditional access policy enforcing multi-factor authentication is in force.
    • Microsoft Entra ID Protection can block authentication attempts if this user account is compromised.
    • The user's password is expired and requires a reset.

while this flow seems simpler than the others, applications using these flows often encounter more problems as compared to other flows like authorization code grant. The error handling is also quiet complex (detailed in the sample)

The modern authentication protocols (SAML, WS-Fed, OAuth and OpenID), in principal, discourages apps from handling user credentials themselves. The aim is to decouple the authentication method from an app. Microsoft Entra ID controls the login experience to avoid exposing secrets (like passwords) to a website or an app.

This enables IdPs like Microsoft Entra ID to provide seamless single sign-on experiences, enable users to authenticate using factors other than passwords (phone, face, biometrics) and Microsoft Entra ID can block or elevate authentication attempts if it discerns that the user’s account is compromised or the user is trying to access an app from an untrusted location and such.

How to run this sample

To run this sample, you'll need:

  • Visual Studio 2019 or just the .NET Core SDK
  • An Internet connection
  • A Windows machine (necessary if you want to run the app on Windows)
  • An OS X machine (necessary if you want to run the app on Mac)
  • A Linux machine (necessary if you want to run the app on Linux)
  • a Microsoft Entra tenant. For more information on how to get a Microsoft Entra tenant, see How to get a Microsoft Entra tenant
  • A user account in your Microsoft Entra tenant. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, if you signed in to the Microsoft Entra admin center with a Microsoft account and have never created a user account in your directory before, you need to do that now.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-dotnetcore-console-up-v2.git

or download and extract the repository .zip file.

Given that the name of the sample is quiet long, and so are the names of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Operating the sample

When you run the sample, if you are running on a domain joined or Microsoft Entra joined Windows machine, it will display your information as well as the information about your manager.

Step 2: (Optional) Register the sample with your Microsoft Entra tenant

The instructions so far used the sample is for an app in a Microsoft test tenant: given that the app is multi-tenant, anybody can run the sample against this app entry.

There is one project in this sample. To register it, you can:

Expand this section if you want to use this automation:
  1. On Windows, run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.

  4. In PowerShell run:

    cd .\AppCreationScripts\
    .\Configure.ps1

    Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

  5. Open the Visual Studio solution and click start to run the code.

Follow the steps below to manually walk through the steps to register and configure the applications.

Choose the Microsoft Entra tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Microsoft Entra tenant.

Register the client app (up-console)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. In the Register an application page that appears, enter your application's registration information:

    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example up-console.
    • Under Supported account types, select Accounts in any organizational directory.
  4. Select Register to create the application.

  5. In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.

    • In the Advanced settings | Default client type section, flip the switch for Treat application as a public client to Yes.
  6. Select Save to save your changes.

  7. In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the Apis that your application needs.

    • Click the Add a permission button and then,
    • Ensure that the Microsoft APIs tab is selected.
    • In the Commonly used Microsoft APIs section, click on Microsoft Graph
    • In the Delegated permissions section, select the User.Read, User.ReadBasic.All in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom.
  8. At this stage, the permissions are assigned correctly but since the client app does not allow users to interact, the user's themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Click the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all account in the tenant.You need to be an the tenant admin to be able to carry out this operation.

Step 3: Configure the sample to use your Microsoft Entra tenant

Configure the client project

Open the project in your IDE (like Visual Studio) to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the up-console\appsettings.json file
  2. Find the app key ClientId and replace the existing value with the application ID (clientId) of the up-console application copied from the Microsoft Entra admin center.

Step 4: Run the sample

Clean the solution, rebuild the solution, and start it in the debugger.

About the code

The code for handling the token acquisition process is simple, as it boils down to calling the AcquireTokenByUsernamePasswordAsync method of PublicClientApplication class. See the GetTokenForWebApiUsingUsernamePasswordAsync method in PublicAppUsingUsernamePassword.cs.

private async Task<AuthenticationResult> GetTokenForWebApiUsingUsernamePasswordAsync(IEnumerable<string> scopes, string username, SecureString password)
{
     AuthenticationResult result = null;
     try
     {
      result = await App.AcquireTokenByUsernamePasswordAsync(scopes, username, password)
        .ExecuteAsync();
     }
     catch (MsalUiRequiredException ex)
     {
       ...
       // error handling omited here (see sample for details)
     }
    
    return result;
}

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [azure-active-directory msal dotnet].

If you find a bug in the sample, please raise the issue on GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

More information

For more information about the app registration:

For more information, see MSAL.NET's conceptual documentation:

For more information about the Microsoft identity platform see: