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 APIWe 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:
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:
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.
To run this sample, you'll need:
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.
Step 2: (Optional) Register the sample with your Microsoft Entra tenantThe 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:
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.
Choose the Microsoft Entra tenant where you want to create your applicationsAs a first step you'll need to:
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:
up-console
.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.
Treat application as a public client
to Yes.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.
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".
up-console\appsettings.json
fileClientId
and replace the existing value with the application ID (clientId) of the up-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; }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.
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:
For more information, see MSAL.NET's conceptual documentation:
For more information about the Microsoft identity platform see:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4