Site icon Rajeev Singh | Coder, Blogger, YouTuber

Integrating Azure AD Authentication in ASP.NET Core : A Guide to Secure User Sign-In

Overview:

In this post, we are going to use Authentication for an ASP. Net app that signs in Azure AD users. It uses MSAL as an Authentication solution. 

Demo (Summary)

  1. Register an application with the Microsoft identity platform.
  2. Prepare a web application for authentication – Microsoft identity platform.
  3. Add sign in to an application – Microsoft identity platform.
  4. Call an API and display the results – Microsoft identity platform. 
Step#StepStep Desc
 1Register your appTutorial: Register an application with the Microsoft identity platform – Microsoft identity platform | Microsoft Learn   Register a web application in a tenant.
Record the web application’s unique identifiers.
Directory (tenant) ID: <>
Application (client) ID: <The application ID from the application registered in the Azure portal.>
Add a platform redirect URI  
 
 2Prepare your appTutorial: Prepare a web application for authentication – Microsoft identity platform | Microsoft Learn    
Create an ASP.NET Core Web App
Create a self-signed certificate
Configure the settings for the application (appsetting.json) TenantId, ClientId, Cert.Thumprint
Define platform settings and URLs(launchSettings.json, Redirect url and Logout URL)  

Add a platform redirect URI Redirect URI: https://localhost:{port}/signin-oidc  
Front-channel logout URI   https://localhost:{port}/signout-oidc        
When you mention the Authentication, urls, You also define the Flow (implicit flow etc.
   
 3Sign in usersTutorial: Add sign in to an application – Microsoft identity platform | Microsoft Learn  
Identify and install the NuGet packages that are needed for authentication:  
 Microsoft.Identity.Web.UI    
Implement authentication in the code: Program.cs
//Add msal
//Controller for Sign in-out
//enable_authz_capabilities  
Add the sign in and sign out experiences _LoginPartial.cshtml  
//to display the user
Hello @user.Identity?.Name!      
 
 4Get user data from web APITutorial: Call an API and display the results – Microsoft identity platform | Microsoft Learn  

Call the API and display the results Index.cshtml.cs  

public async Task OnGet()  
if (response.StatusCode == System.Net.HttpStatusCode.OK) { var apiResult = await response.Content.ReadFromJsonAsync<JsonDocument>().ConfigureAwait(false); ViewData[“ApiResult”] = JsonSerializer.Serialize(apiResult, new JsonSerializerOptions { WriteIndented = true }); }     Index.cshtml     <p><pre><code class=”language-js”>@ViewData[“ApiResult”]</code></pre></p>  

Test the application   https://localhost:7100            
 

Demo (step-by-step)

We will use the below 4 Steps to implement an end-to-end Authentication Solution.

  1. Register an application with the Microsoft identity platform. 
  2. Prepare a web application for authentication – Microsoft identity platform.
  3. Add sign in to an application – Microsoft identity platform.
  4. Call an API and display the results – Microsoft identity platform.

Let’s explore these steps in detail.

Step1: Register an application with the Microsoft identity platform. 

You need to First Register the app, and using Microsoft Entra admin center

Login to Microsoft Entra admin center:

If you have multiple login (including Azure portal), switch to the user that has Subscription and now you can register the user.

Another option is to Register app when you already created it, using the link-> Tutorial – Add app authentication to a web app on Azure App Service – Azure App Service | Microsoft Learn

Register an app.

Click on Register.

What are the activities you perform when you do App Registration?

Below are the activities:

Branding

Authentication

Certificates & secrets

Token configuration

 Step2: Prepare a web application for authentication – Microsoft identity platform.

After registration is complete, an ASP.NET web application can be created using an integrated development environment (IDE). 

a.       Create and upload a self-signed certificate

The use of certificates is a suggested way of securing communication between client and server. For the purpose of this tutorial, a self-signed certificate will be created in the project directory

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

b.       Upload certificate to the portal

To make the certificate available to the application, it must be uploaded into the tenant.

Starting from the Overview page of the app created earlier, under Manage, select Certificates & secrets and select the Certificates (0) tab.

Select Upload certificate.

Screenshot of uploading a certificate into a Microsoft Entra tenant.

c.        Configure the application for authentication and API reference

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

The values recorded earlier will be used in appsettings.json to configure the application for authentication. 

appsettings.json is a configuration file that is used to store application settings used during run-time.

As the application will also call into a web API, it must also contain a reference to it.

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

Instance –The authentication endpoint. Check with the different available endpoints in National clouds. 
TenantId –The identifier of the tenant where the application is registered.  

Replace the text in quotes with the Directory (tenant) ID value that was recorded earlier from the overview page of the registered application.
 
ClientId –The identifier of the application, also referred to as the client.  

Replace the text in quotes with the Application (client) ID value that was recorded earlier from the overview page of the registered application.
 
ClientCertificates – A self-signed certificate is used for authentication in the application.  

Replace the text of the CertificateThumbprint with the thumbprint of the certificate that was previously recorded.
 
CallbackPath –Is an identifier to help the server redirect a response to the appropriate application.     
DownstreamApi – Is an identifier that defines an endpoint for accessing Microsoft Graph. The application URI is combined with the specified scope.    
To define the configuration for an application owned by the organization, the value of the Scopes attribute is slightly different.
 

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

  1. In the Properties folder, open the launchSettings.json file.
  1. Find and record the https value applicationURI within launchSettings.json, for example https://localhost:{port}.
  2.  This URL will be used when defining the Redirect URI.

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

d.       Define the platform and URLs

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

Under Redirect URIs, enter the applicationURL and the CallbackPath, /signin-oidc, in the form of https://localhost:{port}/signin-oidc.

Under Front-channel logout URL, enter the following URL for signing out, https://localhost:{port}/signout-oidc.

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-prepare-app?tabs=visual-studio>

 Step3: Add sign in to an application – Microsoft identity platform.

This tutorial will install the required packages and add code that implements authentication to the sign in and sign out experience.

 install the NuGet packages

Microsoft.Identity.Web.UI

Microsoft.Identity.Web.Diagnostics

Microsoft.Identity.Web.DownstreamApi

Select the Project checkbox, and then select Install.

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-sign-in-users?tabs=visual-studio>

Earlier Code:

Implement authentication and acquire tokens

  1. Open Program.cs and replace the entire file contents with the following snippet:

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-sign-in-users?tabs=visual-studio>

Add the sign in and sign out experience

After installing the NuGet packages and adding necessary code for authentication, add the sign in and sign out experiences.

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-sign-in-users?tabs=visual-studio>

Step4: Call an API and display the results

The application can now be configured to call an API. For the purposes of this tutorial, the Microsoft Graph API will be called to display the profile information of the logged-in user.

 Call the API and display the results

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-call-api?tabs=visual-studio%2Cdotnet6>

You may get below error:

Add below line:

@using sign_in_webapp.Pages;

Validate the app

From <https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-call-api?tabs=visual-studio%2Cdotnet6>

Added Logo so can see new Image/Branding!

Good Job!

You have successfully created an ASP.net Web app that signs in in Azure AD/Entra ID.

Recap:

Lets recap, what we did !

Registering an Application with Azure AD

1. Open Azure Portal: Begin by logging into your Azure account through the Azure Portal.

2. Select Azure Active Directory: After logging in, navigate to the Azure AD section.

3. Click on “App registrations”: In the Azure AD section, click on “App registrations” in the left-hand menu.

4. Click on “New registration”: In the App registrations page, click on the “New registration” button.

5. Enter Application Details: Provide the necessary information for your application, including a name, logo, and description.

6. Choose a subscription: Select the Azure AD subscription under which you want to create the application.

7. Select the “Web app / API” option: From the “Register an application” page, select “Web app / API” as the app. type.

8. Provide Redirect URIs: In the “Redirect URIs” section, enter the redirect URIs that will be associated with your application. For ASP.NET Core applications, it is recommended to use “https://localhost:44300/signin-oidc” as the redirect URI.

9. Click on “Register”: Once you have completed all the necessary information, click on the “Register” button to create the application.

Adding a Redirect URI

1. Open Visual Studio: Open Visual Studio and create a new ASP.NET Core web application.

2. Modify the Startup.cs file: In the Startup.cs file, modify the ConfigureServices method to include the Microsoft Authentication Library for .NET.

3. Import Dependencies: Import the necessary dependencies for Microsoft Authentication Library and Microsoft Identity Web.

4. Configure Authentication: Use the Microsoft Authentication Library’s AuthenticationBuilder to configure authentication using Azure AD.

5. Add Redirect URI: In the Configure method, add the necessary redirect URI for Azure AD authentication.

6. Customize Sign-in and Sign-out: Customize the SignInManager and SignOutManager methods to handle authentication and sign-out events.

7. Publish the Application: Build and publish the application to the desired location.

Implementing Credentials for Secure User Sign-ins

1. Open Azure Portal: Open the Azure Portal and navigate to your application’s registration page.

2. Select “API permissions”: In your application registration page, select “API permissions” from the left-hand menu.

3. Enable required permissions: Enable the necessary API permissions required for your application. For ASP.NET Core applications, it is recommended to enable the following permissions:

– User.Read

– User.ReadWrite

– Directory.Read.All

4. Click on “Add”: Click on the “Add” button to add the specified permissions to your application.

5. Save changes: Save the changes made in the API permissions section.

Conclusion

In the realm of modern web applications, security is paramount. The Microsoft identity platform offers a robust solution for developers seeking to integrate Azure Active Directory (Azure AD) authentication into their ASP.NET Core applications. 

By following this post, you can easily integrate Azure AD authentication into their ASP.NET Core applications.

By leveraging the Microsoft identity platform and the Microsoft Authentication Library for .NET, developers can ensure that their applications are not only secure but also provide a seamless user experience.

As we increasingly embrace cloud technologies, the importance of such identity and access management solutions becomes increasingly critical in protecting both user data and application integrity.

Stay tuned for upcoming post on Authentication!

References:

Quickstart: Sign in to a web app & call an API – ASP.NET Core – Microsoft identity platform | Microsoft Learn

Exit mobile version