Header Ads

C#.NET: Access OAuth REST Web API Method

OAuth is a token base 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 authorization step every time the REST Web API is called. Authentication is still there which is now replace with the generated authorize token available for certain period.

Today, I shall be demonstrating consumption of OAuth 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.

Download Now!

Let's begin now.

1) Create new C#.NET Console Application project and name it "AccessOAuthRESTApi".
  
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.

3) Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.

4) Create "GetAuthorizeToken(...)" method in "Program.cs" file and replace 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>> allIputParams = new List<KeyValuePair<string, string>>();

                // Convert Request Params to Key Value Pair.
...
                // URL Request parameters.
                HttpContent requestParams = new FormUrlEncodedContent(allIputParams);

                // HTTP POST
                response = await client.PostAsync("Token", requestParams).ConfigureAwait(false);

                // Verification
                if (response.IsSuccessStatusCode)
                {
                     // Reading Response.
...
                }
            }

            return responseObj;
        }
...

In the above code, I am using POST type API call to authorize and generate the authorization token, which will be then used to authenticate and access the REST Web API methods. I have also passed the require 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.

5) Now, create "GetInfo(...)" method in "Program.cs" file and replace 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 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.

6) In "Program.cs" file "Main" method write following line of code to first generate authorize 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.
...
                // Call REST Web API method with authorize access token.
                string responseObj = Program.GetInfo(obj.access_token).Result;

                // Process Result.                
...

In the above lines of code, I am generating authorize access token first and after process the response packet, I am calling GET type REST web API method and process my response accodringly.
7) If you execute the provided solution, you will be able to see 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 base 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 authorize access token for REST Web API methods authentication and finally you will also learn to call GET type REST web API with access token for authentication.

5 comments:


  1. Nice blog on the web. Today, Emblix solutions as one of the best and top most service-oriented Digital Marketing Agency in Hyderabad and India, Which provides high-quality result-oriented Digital Services ranging from SEO to Web Design, Social Media Marketing and more,

    ReplyDelete

  2. Thanks for sharing the comprehensive post, your post having informative&valuable content,it will be helpfull. |
    Web DesignCompany in Hyderabad

    ReplyDelete
  3. useful information, thanks for the sharing, keep going.
    digital marketing services in hyderabad

    ReplyDelete
  4. Very Informative Article. Worth visiting as well as worth Recommending. Thanks to you for sharing this helpful information with us. Keep posting. Plots in Shadnagar

    ReplyDelete
  5. The article was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents.
    By Cloudi5 Web Design Company in Coimbatore

    ReplyDelete