4 min read

Auth Series #2 - Protect ASP.NET Core Api with Microsoft Entra ID and Access It via Postman

Auth Series #2 - Protect ASP.NET Core Api with Microsoft Entra ID and Access It via Postman

Auth Series #2 - Protect ASP.NET Core Api with Microsoft Entra ID and Access It via Postman

This is the 2nd tutorial of the Auth Series. In this tutorial, we’ll create a basic ASP.NET Core Web Api and protect it using Azure AD/Microsoft Entra ID. If you want to know how to protect web app with Azure AD/Microsoft Entra ID, you can checkout our previous tutorial: Auth Series #1 - Azure Entra Id Authentication using ASP.NET Core MVC

Requirements:

- Web Framework: ASP.NET Core 7x Api Default Project
- Nuget: Microsoft.Identity.Web


We are going to make a simple WeatherForecast Api and protect it using JWT Bearer/Oauth via Microsoft Entra ID / Azure ID and we will then call the api endpoint via Postman.

Before we move further, let’s start with the first step.

1. Create a Web Api Registration

We need to create an api registration in the Azure Portal so that we can protect our api. First, we need to go to Microsoft Entra ID Portal > App Registrations > New registration.

2024 01 11 17H17 43

In this tutorial, we will use uptec-auth-api as the name but you can use any name you want. Leave other options as is and click Register.

2024 01 11 17H21 01

After it has been created, you should take a note of the Client Id and Tenant Id for our api appsettings.json.

2024 01 11 17H21 15

Now, go to Expose an API > Add Application ID URI and Add a scope. Application ID URI is important as an identifier for our authorisation scope later. And the scope itself is like an attribute that we can use to protect an api as part of authorization. It means that, after an api gets validated (JWT Token validated), we can check its scope in the JWT token as well. If it has the same scopes that we’ve registered, the request can be continued. Otherwise, the request can be stopped and 403-forbidden will be issued.

2024 01 11 17H23 20

Add the Application ID URI like the image below.

2024 01 11 17H23 45

After that, add a new scope, give it a name -> Access.Read and fill the other information like Title and Description like in the screenshot below.

2024 01 11 17H25 22

Once created, don’t forget to copy/take a note of the scope for later use.

2. Create Web Api Project

Now, we are will create an ASP.NET Core Web API project. In this section, I will use .NET 7.

Open Visual Studio, Select ASP.NET Core Web API project. Give it a name, and make sure to leave other options as per screenshots below.

2024 01 11 17H26 56

2024 01 11 17H27 11

2024 01 11 17H27 22

Once the project is initialised, modify the appsettings.json and add the below section.

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "",
    "ClientId": "",
    "Scopes": "api://<GUID>/Access.Read" 
  }

Make sure you copy past the TenantId, ClientId and Scope from our previous #1 section.

2024 01 11 17H29 46

Install the nuget package:

Microsoft.Identity.Web

This library is used to enable JWT Bearer/API Protection using token in our api project.

2024 01 11 17H30 24

To customize the program execution, we need to modify our launchSettings.json. Cleanup everything and leave the “https” section with default port 8181.

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:8181;",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

2024 01 11 17H33 18

3. Register the MicrosoftIdentityWebApiAuthentication

Once the above setup is completed, we will enable the api protection by customising the Program.cs file. Add the following namespace:

using Microsoft.Identity.Web;

Then add the following code to register the MicrosoftIdentityWebApiAuthentication to enable api authentication/protection using JWT Token from Microsoft Entra ID/Azure AD.

services
    .AddMicrosoftIdentityWebApiAuthentication(configuration, "AzureAd");

2024 01 11 17H35 10

The above snippet will read our configuration section of AzureAd in appsettings.json file.

4. Protect WeatherForecast Sample API

The last step is to mark our controller as Authorized. It means, only authenticated members are allowed to access the endpoint.

2024 01 11 17H35 36

5. Test The App - Got 401 Unauthorised

Now we will test the app using Postman. And because we are not authenticated, of course we’ll get 401.

2024 01 11 17H42 18

6. Create New App Registration For Postman (Microsoft Entra ID)

Ok, because we got 401, we need our Postman to be authenticated to access the endpoint. To do this we will create new App Registration specially for any clients that will access any protected apis that we define.

Give the name anything but ended with -caller (optional - previous app registration was uptect-auth-api).

2024 01 11 17H42 29

Once created, take a note on those client id and tenant id.

2024 01 11 17H42 43

Create the client secret and take a note of it in Certificate & secrets menu.

2024 01 11 17H43 23

2024 01 11 17H43 41

For Postman to work, we need to register the callback url in the Authentication menu. Paste the below url:

https://oauth.pstmn.io/v1/callback

2024 01 11 17H44 52 2024 01 11 17H45 56

After we have defined our callback url, we need to make sure our Postman’s app registration can easily access our Protected Api’s app registration. We need to request api permissions for our api’s scope we defined earlier in the beginning. Go to API Permissions menu, select Add a permission button, in the APIs my organization uses type your previous api’s app registration name and select it.

2024 01 11 17H48 20

Once selected, choose the permission that we defined earlier.

Access.Read

2024 01 11 17H48 54

The last step is to grant admin consent for requested api’s scope(s).

2024 01 11 17H49 21

7. Access the Protected API via Postman

After step #6 is completed, we can now access the api with Postman. To do so, we need to collect the OAuth v2 authorization and token endpoints from our api’s app registration.

Take a note of both the OAuth v2 authorization and token endpoints like the image below:

NB: This is api’s app registration not Postman’s app registration

2024 01 11 17H50 19

The next step is to go the our previous Postman, in the Authorization section, choose the OAuth 2.0 type.

2024 01 11 17H52 28

Now, fill the information in the section below:

2024 01 11 17H54 29


- Auth Url -> Authorization endpoint of api's app registration.
- Access Token URL -> Token endpoint of api's app registration.
- Client ID -> client id of our Postman
- Client Secret -> client secret of our postman
- Scope -> scope of the api - api://(GUID)/Access.Read


After that, scroll down and click the Get New Access Token. It will authenticate using browser. And on the successful sign-in, make sure you proceed and click Use Token button.

2024 01 11 17H54 58

2024 01 11 17H55 15

2024 01 11 17H55 39

2024 01 11 17H55 45

Ok, if no issues, we can now test to call our api endpoint.

2024 01 11 17H56 30

We can also copy paste our access token in the https://jwt.ms to inspect the payload information of it.

2024 01 11 17H56 59

2024 01 11 17H57 28

In the next tutorial, we will be accessing our protected api via console application built on top of .NET Core 7x.

Sample project: https://github.com/mirzaevolution/Uptec-Protected-Web-Api

Regards,

Mirza Ghulam Rasyid

Auth Series #5 - Call Microsoft Entra ID/Azure AD Protected Web API via ASP.NET Core MVC using Authorization Code Flow

9 min read

Auth Series #5 - Call Microsoft Entra ID/Azure AD Protected Web API via ASP.NET Core MVC using Authorization Code Flow

Auth Series #5 - Call Microsoft Entra ID/Azure AD Protected Web API via ASP.NET Core MVC using Authorization Code Flow This is the 5th tutorial...

Read More
Auth Series #1 - Microsoft Entra ID Authentication using ASP.NET Core MVC

3 min read

Auth Series #1 - Microsoft Entra ID Authentication using ASP.NET Core MVC

Auth Series #1 - Microsoft Entra ID Authentication using ASP.NET Core MVC This tutorial will be a series of blog posts to cover some common...

Read More
Auth Series #6 - Secure Open API (Swagger) calls with Microsoft Entra ID/Azure AD

3 min read

Auth Series #6 - Secure Open API (Swagger) calls with Microsoft Entra ID/Azure AD

Auth Series #6 - Secure Open API (Swagger) calls with Microsoft Entra ID/Azure AD This is the 6th tutorial of the Auth Series. Previously in the...

Read More