OAuth is a token-based authorization mechanism for REST Web API. You develop the authorization with the API only once, up until the token expires. 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 and has been replaced with the generated authorized token that is available for a certain period.
Today, I shall be demonstrating the consumption of OAuth token-based authorization for REST Web API methods using a C#.NET Console Application.
Prerequisites
The following are some prerequisites before you proceed any further in this tutorial.
- Understanding of JSON Object Mapper.
- Knowledge of REST Web API.
- Knowledge of ASP.NET MVC5.
- 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 on the server side.
Let's begin now.
Step 1. Create a new C#.NET Console Application project and name it "AccessOAuthRESTApi".
Step 2. Create target JSON object mappers for request/response objects 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 the "GetAuthorizeToken(...)" method in the "Program. cs" file and replace the following code in it i.e.
public static async Task<string> GetAuthorizeToken()
{
// Initialization
string responseObj = string.Empty;
// Posting
using (var client = new HttpClient())
{
// Setting Base address
client.BaseAddress = new Uri("http://localhost:3097/");
// Setting content type
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Initialization
HttpResponseMessage response = new HttpResponseMessage();
List<KeyValuePair<string, string>> allInputParams = new List<KeyValuePair<string, string>>();
// Convert Request Params to Key Value Pair (missing implementation)
// URL Request parameters
HttpContent requestParams = new FormUrlEncodedContent(allInputParams);
// HTTP POST
response = await client.PostAsync("Token", requestParams).ConfigureAwait(false);
// Verification
if (response.IsSuccessStatusCode)
{
// Reading Response (missing implementation)
}
}
return responseObj;
}
In the above code, I am using a 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 the access token type and expiration.
Step 5. Now, create the "GetInfo(...)" method in the "Program. cs" file and replace the following code in it i.e.
...
public static async Task<string> GetInfo(string authorizeToken)
{
// Initialization.
string responseObj = string.Empty;
// HTTP GET.
using (var client = new HttpClient())
{
// Initialization
string authorization = authorizeToken;
// Setting Authorization.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorization);
// Setting Base address.
client.BaseAddress = new Uri("https://localhost:44334/");
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Initialization.
HttpResponseMessage response = new HttpResponseMessage();
// HTTP GET
response = await client.GetAsync("api/WebApi").ConfigureAwait(false);
// Verification
if (response.IsSuccessStatusCode)
{
// Reading Response.
...
}
}
return responseObj;
}
...
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 called my REST Web API, and finally, I read the response and processed it according to my business requirements.
Step 6. In the "Program. cs" file "Main" method, write the following line of code to first generate an authorized access token and then call the GET type REST Web API method i.e.
// Generate Authorize Access Token to authenticate REST Web API.
string oAuthInfo = Program.GetAuthorizeToken().Result;
// Process response access token info (missing implementation)
// Call REST Web API method with authorize access token.
string responseObj = Program.GetInfo(oAuthInfo).Result;
// Process Result (missing implementation)
In the above lines of code, I generate an authorized access token first, and after processing the response packet, I call the GET type REST web API method and process 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 the "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 tokens for authentication.