C#.NET - Access OAuth REST Web API Method

OAuth is a token based authorization mechanism for REST Web API. You develop the authorization with the API only once up until the expiration time of the token. The generated token is then used each time the REST Web API is called, saving an authorization step every time the REST Web API is called. Authentication is still there which is now replaced with the generated authorized token available for a certain period.
 
Today, I shall be demonstrating consumption of OAuth token-based authorization for REST Web API methods using C#.NET Console Application.
 
 
Prerequisites
 
Following are some prerequisites before you proceed any further in this tutorial:
  1. Understanding of JSON Object Mapper.
  2. Knowledge of REST Web API.
  3. Knowledge of ASP.NET MVC5.
  4. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional. I have used ASP.NET MVC - OAuth 2.0 REST Web API Authorization solution as server side.
 
Let's begin now.
 
Step 1
 
Create new C#.NET Console Application project and name it "AccessOAuthRESTApi".  
 
Step 2
 
Create target JSON object mappers for request/response objects as according to ASP.NET MVC - OAuth 2.0 REST Web API Authorization server side solution.
 
Step 3
 
Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.
 
Step 4
 
Create "GetAuthorizeToken(...)" method in "Program.cs" file and replace following code in it i.e.:
  1. ...  
  2.         public static async Task<string> GetAuthorizeToken()  
  3.         {  
  4.             // Initialization.  
  5.             string responseObj = string.Empty;  
  6. ...  
  7.             // Posting.  
  8.             using (var client = new HttpClient())  
  9.             {  
  10.                 // Setting Base address.  
  11.                 client.BaseAddress = new Uri("http://localhost:3097/");  
  12.   
  13.                 // Setting content type.  
  14.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  15. ...  
  16.                 // Initialization.  
  17.                 HttpResponseMessage response = new HttpResponseMessage();  
  18.                 List<KeyValuePair<stringstring>> allIputParams = new List<KeyValuePair<stringstring>>();  
  19.   
  20.                 // Convert Request Params to Key Value Pair.  
  21. ...  
  22.                 // URL Request parameters.  
  23.                 HttpContent requestParams = new FormUrlEncodedContent(allIputParams);  
  24.   
  25.                 // HTTP POST  
  26.                 response = await client.PostAsync("Token", requestParams).ConfigureAwait(false);  
  27.   
  28.                 // Verification  
  29.                 if (response.IsSuccessStatusCode)  
  30.                 {  
  31.                      // Reading Response.  
  32. ...  
  33.                 }  
  34.             }  
  35.   
  36.             return responseObj;  
  37.         }  
  38. ... 
In the above code, I am using POST type API call to authorize and generate the authorization token, which will then be used to authenticate and access the REST Web API methods. I have also passed the required authorization scheme and authorization credentials to the API server as a key value pair. The returning JSON packet will provide the access token along with access token type and expiration.
 
Step 5
 
Now, create "GetInfo(...)" method in "Program.cs" file and replace the following code in it i.e.:
  1. ...  
  2.         public static async Task<string> GetInfo(string authorizeToken)  
  3.         {  
  4.             // Initialization.  
  5.             string responseObj = string.Empty;  
  6.   
  7.             // HTTP GET.  
  8.             using (var client = new HttpClient())  
  9.             {  
  10.                 // Initialization  
  11.                 string authorization = authorizeToken;  
  12.   
  13.                 // Setting Authorization.  
  14.                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorization);  
  15.   
  16.                 // Setting Base address.  
  17.                 client.BaseAddress = new Uri("https://localhost:44334/");  
  18.   
  19.                 // Setting content type.  
  20.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  21.   
  22.                 // Initialization.  
  23.                 HttpResponseMessage response = new HttpResponseMessage();  
  24.   
  25.                 // HTTP GET  
  26.                 response = await client.GetAsync("api/WebApi").ConfigureAwait(false);  
  27.   
  28.                 // Verification  
  29.                 if (response.IsSuccessStatusCode)  
  30.                 {  
  31.                     // Reading Response.  
  32. ...  
  33.                 }  
  34.             }  
  35.   
  36.             return responseObj;  
  37.         }  
  38. ... 
In the above code, I am first providing an authorized access token, which I have just generated to my REST Web API call for authentication. Then, I call  my REST Web API and finally, I read the response and process my response according to my business requirements.
 
Step 6
 
In "Program.cs" file "Main" method write the  following line of code to first generate authorized access token and then call the GET type REST Web API method i.e.:
  1. ...  
  2.                 // Generate Authorize Access Token to authenticate REST Web API.  
  3.                 string oAuthInfo = Program.GetAuthorizeToken().Result;  
  4.   
  5.                 // Process response access token info.  
  6. ...  
  7.                 // Call REST Web API method with authorize access token.  
  8.                 string responseObj = Program.GetInfo(obj.access_token).Result;  
  9.   
  10.                 // Process Result.                  
  11. ... 
In the above lines of code, I am generating authorized access token first and after processing the response packet, I am calling GET type REST web API method and processing my response accordingly.
 
Step 7 
 
If you execute the provided solution, you will be able to see the following, but, you will need to execute the ASP.NET MVC - OAuth 2.0 REST Web API Authorization server side solution first i.e.:
 

Conclusion

 
In this article, you will learn to consume OAuth token based authorization type API for REST Web API methods using C#.NET Console Application. You will also learn to utilize "HttpClient" library to consume REST Web APIs. You will learn to generate authorized access tokens for REST Web API method authentication and finally you will also learn to call GET type REST web API with access token for authentication.