Site icon Rajeev Singh | Coder, Blogger, YouTuber

Creating Protected Web API using OAuth2

Overview:

In this blog post, we will cover how to both expose and protect your ASP.NET Core web API. By following these instructions, you will enable authenticated users to access only the resources they are authorized to.

Firstly, we will cover the topic to Protect an ASP.NET Core Web API with the Microsoft Identity Platform:

We will explore and demonstrate how to protect an ASP.NET Core web API using the Microsoft identity platform for authorization.

You’ll register an application, record identifiers, and expose an API.

The sample uses ASP.NET Core Identity and Microsoft Authentication Library (MSAL) for authentication.

Prerequisites include an Azure account and .NET 6.0 SDK.

And then we will explore how to access protected ASP.NET Web API with cURL, We will also explore and validate Web API using Postman.

Specifics

The specific information you need to know to protect web APIs are:

won’t be supported.

Prerequisites:

Demo (Summary):

Step 1: Clone a repo/App setup.

Step 2: Expose an API.

Step 3: Add a scope.

Step 4: Validate Web API (using cURL command in Bash)

Step 5: Validate using Postman.

Demo(step-by-step):

Let’s get started with the demo, below is the summary.

Step 1: Clone a repo/App setup.

We will use an ASP.NET Core web API code sample to demonstrate how to restrict resource access to authorized accounts.

The sample uses ASP.NET Core Identity that interacts with Microsoft Authentication Library (MSAL) to handle authentication.

Below are the activities to be performed.

  1. Downloads the code
  2. Register app
  3. Expose an API-> Add a scope
  4. Access API using Postman

Instancehttps://login.microsoftonline.com/
Client ID32fe5463-64df-4db8-bf66-9a70af9b5b93
Tenant ID8b79fff2-1096-425e-ae24-10b08624fa9d
ScopeForecast.Read
Logging 
AllowedHosts*

Step 2: Expose an API

Once the API is registered, you can configure its permission by defining the scopes that the API exposes to client applications.

Client applications request permission to perform operations by passing an access token along with its requests to the protected web API. The web API then performs the requested operation only if the access token it receives contains the required scopes.

  1. Under Manage, select Expose an API > Add a scope. Accept the proposed Application ID URI (api://{clientId}) by selecting Save and continue. The {clientId} is the value recorded from the Overview page. Then enter the following information:
  2. For Scope name, enter Forecast.Read.
  3. For Who can consent, ensure that the Admins and users option is selected.
  4. In the Admin consent display name box, enter Read forecast data.
  5. In the Admin consent description box, enter Allows the application to read weather forecast data.
  6. In the User consent display name box, enter Read forecast data.
  7. In the User consent description box, enter Allows the application to read weather forecast data.
  8. Ensure that the State is set to Enabled.
  9. Select Add scope. If the scope has been entered correctly, it’s listed in the Expose an API pane.

Step 3: Add a scope

Note: This Demo doesn’t cover below:

Code behind:

Let’s understand the code behind.

Code summary: 

ID#CodeDesc
1It uses below library    
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Web;  
Its used to get the Jwt Tokens
2Read all the AzureAd config details (clintId, Teneant Id)  
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)                 .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(“AzureAd”));  
Add services to the container.      
3Use Auth and Auth methods.     
4Write your API code  
5 App.Run(); 

What are the Nuget Packages required?

Tools-> Nuget Package Manager ->

In the top menu, select Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

With the Browse tab selected, search for Microsoft.Identity.Web, select the Microsoft.Identity.Web package, select the Project checkbox, and then select Install.

Validate

To verify the endpoint is protected, use the following cURL command in Bash to send an unauthenticated HTTP GET request in Bash:

Configure an authorized request to the web API in Postman

 Get a new access token.

You will see below screen as Authentication complete.

 Copy the Access Token.

 And send the request now along with Access token in Header.

Access token is validated, and you will see the Response as shown below. 

Completed Successfully!

As you can see, when you pass the bearer token in request header and request for the API, API validates the token and returns the Response, success and the response body.

In case token is not correct, it will return fail with failed response body, error message.

Conclusion

In this blog post, we explored how to validate these Protected Web APIs using cURL and Postman. These tools provide an effective way to test the API’s functionality and validate its responses. By executing the API requests through cURL and Postman, developers can gain insights into the API’s performance and identify any potential issues.

In upcoming posts, we will explore how to consume/call these Protected APIs from any front-end application, such as a web application or a Windows app. Developing applications that communicate with the API is crucial for leveraging its features and capabilities. By understanding how to consume the API, developers can build seamless integrations and create innovative applications that leverage the Protected API’s features.

Stay tuned for our upcoming posts, where we will explore the necessary steps to consume the Protected API and demonstrate how it can be integrated into different front-end applications.

Happy coding! 🚀🔐👨‍💻

References:

https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-web-api-aspnet-core-protect-api

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

https://learn.microsoft.com/en-us/entra/identity-platform/howto-call-a-web-api-with-curl?source=recommendations&tabs=dotnet6&pivots=no-api

Exit mobile version