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:
- Understanding of JSON Object Mapper.
- Knowledge of REST Web API.
- Knowledge of ASP.NET MVC5.
- Knowledge of C# Programming.
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.:
- ...
- public static async Task<string> GetAuthorizeToken()
- {
-
- string responseObj = string.Empty;
- ...
-
- using (var client = new HttpClient())
- {
-
- client.BaseAddress = new Uri("http://localhost:3097/");
-
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- ...
-
- HttpResponseMessage response = new HttpResponseMessage();
- List<KeyValuePair<string, string>> allIputParams = new List<KeyValuePair<string, string>>();
-
-
- ...
-
- HttpContent requestParams = new FormUrlEncodedContent(allIputParams);
-
-
- response = await client.PostAsync("Token", requestParams).ConfigureAwait(false);
-
-
- if (response.IsSuccessStatusCode)
- {
-
- ...
- }
- }
-
- return responseObj;
- }
- ...
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.:
- ...
- public static async Task<string> GetInfo(string authorizeToken)
- {
-
- string responseObj = string.Empty;
-
-
- using (var client = new HttpClient())
- {
-
- string authorization = authorizeToken;
-
-
- client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorization);
-
-
- client.BaseAddress = new Uri("https://localhost:44334/");
-
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
-
- HttpResponseMessage response = new HttpResponseMessage();
-
-
- response = await client.GetAsync("api/WebApi").ConfigureAwait(false);
-
-
- if (response.IsSuccessStatusCode)
- {
-
- ...
- }
- }
-
- 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 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.:
- ...
-
- string oAuthInfo = Program.GetAuthorizeToken().Result;
-
-
- ...
-
- string responseObj = Program.GetInfo(obj.access_token).Result;
-
-
- ...
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.