page_type | languages | products | description | urlFragment | |||
---|---|---|---|---|---|---|---|
sample |
|
|
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
We have renamed the default branch to main. To rename your local repo follow the directions here.
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)
If you would like to get started immediately, skip this section and jump to How To Run The Sample.
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.
- Developers who wish to gain good familiarity of programming for Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.
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.
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.
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.
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:
- either follow the steps Step 2: Register the sample with your Microsoft Entra tenant and Step 3: Configure the sample to use your Microsoft Entra tenant
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you. Note that this works for Visual Studio only.
- modify the Visual Studio projects' configuration files.
Expand this section if you want to use this automation:
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
-
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.
-
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.
As a first step you'll need to:
- Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
- 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.
-
Navigate to the Microsoft identity platform for developers App registrations page.
-
Select New registration.
-
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.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
-
Select Register to create the application.
-
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.
- In the Advanced settings | Default client type section, flip the switch for
-
Select Save to save your changes.
-
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.
-
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.
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".
- Open the
up-console\appsettings.json
file - Find the app key
ClientId
and replace the existing value with the application ID (clientId) of theup-console
application copied from the Microsoft Entra admin center.
Clean the solution, rebuild the solution, and start it in the debugger.
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;
}
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.
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.
For more information about the app registration:
- Microsoft identity platform
- Quickstart: Register an application with the Microsoft identity platform
- Quickstart: Configure a client application to access web APIs
For more information, see MSAL.NET's conceptual documentation:
- MSAL.NET's conceptual documentation
- Customizing Token cache serialization
- Scenarios
- Acquiring Tokens
- Username/password
- Microsoft identity platform and the OAuth 2.0 resource owner password credential to learn more about the underlying protocol
- Resource owner password credentials RFC
For more information about the Microsoft identity platform see: