A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/azure-samples/active-directory-dotnetcore-console-up-v2 below:

Azure-Samples/active-directory-dotnetcore-console-up-v2: A .NET Core console application which gets an access token to call Microsoft Graph using a username and password

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

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:

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:

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.

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:

  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.

  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.

  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.

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