×

iFour Logo

How to use Database First Approach in Asp.Net MVC to authorize OAuth 2.0 Rest Web APIs?

Kapil Panchal - September 23, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
How to use Database First Approach in Asp.Net MVC to authorize OAuth 2.0 Rest Web APIs?

The REST Web API is a lightweight and critical component of web development for sharing data on several customer machines and devices, for example, mobile devices, desktop apps, or any Website. The permission of the REST Web API is also important for data sharing between multiple client machines and devices to protect the sensibility of data from all external violations and for authenticating the use of the target REST Web API.

Authorization of the REST Web API can be done through a specific user name/password with the combination of a secret key, but, for such an authorization scheme, Access to the REST Web API shall be authenticated for each call to the hosting server. In addition, we as the server owner have no way of checking who is using our REST Web API, if it is the clients that we have authorized access to or if a malicious user also uses our APIs(s) unbeknownst to us. Finally, since the username/password is automatically packaged as base64 by the browser, if a malicious user traces my browser's activity and gets ahold of my Web REST API calls, they can easily decrypt the base64 format and could use my Web REST API for malicious activities.

I have authorized my Web REST API, it is always open to malicious users to use without even my knowledge. So, what to do? To respond that a new authorization scheme is introduced which can also be used in the Connection workflow of any web application as well, but, I'll focus on it from the point of view of the REST Web API Thus, this new permission schema is OAuth 2.0 which is a basic token permission schema.

I will demonstrate the OAuth 2.0 mechanism to allow a REST Web API, which will also benefit from the [Authorize] attribute through the OWIN security layer.


Here are some requirements before proceeding:
  1. Familiarity with OAuth 2.0.
  2. Familiar with ASP.NET MVC5.
  3. Familiarity with programming C#.
  4. Familiarity with the REST Web API.

The source code of the currently running workbench is developed in Microsoft Visual Studio 2015 Enterprise and SQL Server 2014 is used for database development.

Let's get started:

1) Create a new Web API project to be called "ApiOAuth".

2) Install the following Nuget packages within your project, ie.

  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Cors
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.Owin

3) Establish a database "DB_Oauth_API" in your SQL server. Comprehensive database scripts are supplied with the solution code. I created a simple login table and storage process to retrieve the specific login. I use the first database approach of the entity framework for connecting to the database for this asp.net. If you have downloaded the supplied solution, also update your SQL server login string to the project "Web. config" file if you have downloaded the project.

4) Rename the "Controllers/ValueController.cs" file as "Controllers/WebApiController.cs".

5) Open the "Controllers/WebApiController.cs" file and override the following:

In the above code, I have created simple and basic Web REST APIs. The Notice [Authorize] attribute is already located at the top of the controller to secure access to the Web REST API(s).

6) Now open the file "App_Start/WebApiConfig.cs" and add two lines of code that will add an authentication filter for the Oauth 2.0 authorization scheme and exceed any existing authorization scheme, i.e.

7) Now open the file "App_Start/Startup.Auth.cs" and add the following lines of code in which "PublicClientId" is used when "AuthorizeEndpointPath" is used for single instantiate on the customer side. The following lines of code will activate the OAuth 2.0 authorization diagram, i.e.

OAuthAuthorizationOptions are described as follows:

TokenEndpointPath: It is the path that will be called to allow user IDs and in return, it will return the generated access token.

Provider: You need to implement this classroom (which I have in this tutorial) where you will check to Provide user credentials and create identity claims to return the generated access token.

AccessTokenExpireTimeSpan: This is the time during which you want your access token to be available. A shorter duration is recommended for responsive API(s).

AllowInsecureHttp: Use this property for the development environment.

8)Now create the file "Helper_Code/OAuth2/AppOAuthProvider.cs" which is the provider class into which you are going to configure the authorization logic. The "GrantResourceOwnerCredentials()" method is the key method that is invoked when TokenEndpointPath is invoked. Notice that the "GrantResourceOwnerCredentials()" method is used with the "grant_type=password" schema. If you use the "grant_type=client_credentials" schema you must override the "GrantClientCredentials()" method. Other inherited methods are included in the class "OAuthAuthorizationServerProvider", use them as they are. In the "GrantResourceOwnerCredentials()” method, the system login user is verified then create the required ID requisitions, then generate the token return ticket, i.e.

9) Now run the project and use the following navigator link to see your new REST Web API method in action as follows

In the excerpt above, you will notice that since now our Web REST API has been allowed, therefore, we cannot directly run the Web REST API URL in the browser.

10) Allows testing of Web REST API on Web REST API client. I use the Firefox plugin e.g. "RESTED". A, first of all, I'm just trying to hit the Web REST API with no authorization details.

11) Now I will provide authorization to the user of the system to obtain an access token and then use this access token as a header within the REST Web API and try its Web REST API.

Notice in the excerpts above that the access token is provided as the "Authorization" header with the "Bearer access_token" schema in order to call the Web REST API. Also note the path when the chip is generated, ie "{your__site_url}/Token".

Learn to implement OAuth 2.0 for secure API authorization in ASP.NET MVC using the Database First approach. Enhance your app's security and functionality with our API Integration Services. Contact us today to streamline your RESTful API integration!

Conclusion


In this blog, we have gone through the integration of OAuth 2.0 authorization schema with ASP.NET MVC REST Web API. We have also learned the short comparison between the basic user/password authorization and the basic OAuth 2.0 token authorization.

How to use Database First Approach in Asp.Net MVC to authorize OAuth 2.0 Rest Web APIs? The REST Web API is a lightweight and critical component of web development for sharing data on several customer machines and devices, for example, mobile devices, desktop apps, or any Website. The permission of the REST Web API is also important for data sharing between multiple client machines and devices to protect the sensibility of data from all external violations and for authenticating the use of the target REST Web API. Authorization of the REST Web API can be done through a specific user name/password with the combination of a secret key, but, for such an authorization scheme, Access to the REST Web API shall be authenticated for each call to the hosting server. In addition, we as the server owner have no way of checking who is using our REST Web API, if it is the clients that we have authorized access to or if a malicious user also uses our APIs(s) unbeknownst to us. Finally, since the username/password is automatically packaged as base64 by the browser, if a malicious user traces my browser's activity and gets ahold of my Web REST API calls, they can easily decrypt the base64 format and could use my Web REST API for malicious activities. I have authorized my Web REST API, it is always open to malicious users to use without even my knowledge. So, what to do? To respond that a new authorization scheme is introduced which can also be used in the Connection workflow of any web application as well, but, I'll focus on it from the point of view of the REST Web API Thus, this new permission schema is OAuth 2.0 which is a basic token permission schema. I will demonstrate the OAuth 2.0 mechanism to allow a REST Web API, which will also benefit from the [Authorize] attribute through the OWIN security layer. Here are some requirements before proceeding: Familiarity with OAuth 2.0. Familiar with ASP.NET MVC5. Familiarity with programming C#. Familiarity with the REST Web API. The source code of the currently running workbench is developed in Microsoft Visual Studio 2015 Enterprise and SQL Server 2014 is used for database development. Read More: A Detailed Guide On Custom Authentication And Authorization In Asp.net Mvc Let's get started: 1) Create a new Web API project to be called "ApiOAuth". 2) Install the following Nuget packages within your project, ie. Microsoft.Owin.Security.OAuth Microsoft.Owin.Cors Microsoft.AspNet.WebApi.Core Microsoft.AspNet.WebApi.Owin 3) Establish a database "DB_Oauth_API" in your SQL server. Comprehensive database scripts are supplied with the solution code. I created a simple login table and storage process to retrieve the specific login. I use the first database approach of the entity framework for connecting to the database for this asp.net. If you have downloaded the supplied solution, also update your SQL server login string to the project "Web. config" file if you have downloaded the project. 4) Rename the "Controllers/ValueController.cs" file as "Controllers/WebApiController.cs". 5) Open the "Controllers/WebApiController.cs" file and override the following: In the above code, I have created simple and basic Web REST APIs. The Notice [Authorize] attribute is already located at the top of the controller to secure access to the Web REST API(s). 6) Now open the file "App_Start/WebApiConfig.cs" and add two lines of code that will add an authentication filter for the Oauth 2.0 authorization scheme and exceed any existing authorization scheme, i.e. 7) Now open the file "App_Start/Startup.Auth.cs" and add the following lines of code in which "PublicClientId" is used when "AuthorizeEndpointPath" is used for single instantiate on the customer side. The following lines of code will activate the OAuth 2.0 authorization diagram, i.e. OAuthAuthorizationOptions are described as follows: TokenEndpointPath: It is the path that will be called to allow user IDs and in return, it will return the generated access token. Provider: You need to implement this classroom (which I have in this tutorial) where you will check to Provide user credentials and create identity claims to return the generated access token. AccessTokenExpireTimeSpan: This is the time during which you want your access token to be available. A shorter duration is recommended for responsive API(s). AllowInsecureHttp: Use this property for the development environment. Searching for Reliable .Net Development Company CONTACT US 8)Now create the file "Helper_Code/OAuth2/AppOAuthProvider.cs" which is the provider class into which you are going to configure the authorization logic. The "GrantResourceOwnerCredentials()" method is the key method that is invoked when TokenEndpointPath is invoked. Notice that the "GrantResourceOwnerCredentials()" method is used with the "grant_type=password" schema. If you use the "grant_type=client_credentials" schema you must override the "GrantClientCredentials()" method. Other inherited methods are included in the class "OAuthAuthorizationServerProvider", use them as they are. In the "GrantResourceOwnerCredentials()” method, the system login user is verified then create the required ID requisitions, then generate the token return ticket, i.e. 9) Now run the project and use the following navigator link to see your new REST Web API method in action as follows In the excerpt above, you will notice that since now our Web REST API has been allowed, therefore, we cannot directly run the Web REST API URL in the browser. 10) Allows testing of Web REST API on Web REST API client. I use the Firefox plugin e.g. "RESTED". A, first of all, I'm just trying to hit the Web REST API with no authorization details. 11) Now I will provide authorization to the user of the system to obtain an access token and then use this access token as a header within the REST Web API and try its Web REST API. Notice in the excerpts above that the access token is provided as the "Authorization" header with the "Bearer access_token" schema in order to call the Web REST API. Also note the path when the chip is generated, ie "{your__site_url}/Token". Learn to implement OAuth 2.0 for secure API authorization in ASP.NET MVC using the Database First approach. Enhance your app's security and functionality with our API Integration Services. Contact us today to streamline your RESTful API integration! Conclusion In this blog, we have gone through the integration of OAuth 2.0 authorization schema with ASP.NET MVC REST Web API. We have also learned the short comparison between the basic user/password authorization and the basic OAuth 2.0 token authorization.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...