×
iFour Logo

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

Hiren Shekhda - September 23, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

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.

Searching for Reliable .Net Development Company ? Your Search ends here.

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".

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 ? Your Search ends here. See here 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". 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.

Author Bio

User Image

Author Name : Hiren Shekhda

Hiren Shekhda is an adroit Asp.Net MVC developer with great exposure to the subject. He shares extremely fabulous insights over different platforms to help learners. Besides, he invests considerable time to learn new things.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

 A step-by-step guide on Excel Add-in development using React.js
A step-by-step guide on Excel Add-in development using React.js

Table of Content 1.What is an Excel Add-in? 2.Prerequisites for setting up your development environment 3.How to build Excel Add-in using React 4.How to run...

Read More
11 Ways AR and VR (Augmented Reality and Virtual Reality) Transforming the Healthcare sector
11 Ways AR and VR (Augmented Reality and Virtual Reality) Transforming the Healthcare sector

Table of Content 1. Helps in surgical procedures and treats phobias 2. Create new training opportunities for doctors 3. Real-time information helps to escape from painful...

Read More
How E-discovery tools can benefit the Legal industry?
How E-discovery tools can benefit the Legal industry?

Table of Content 1.Gather essential information quickly 2.Automate and streamline tedious tasks 3.Save considerable time and money in the discovery process 4.Analyze...

Read More