Consuming Restful API with Bearer Token Authentication using HttpWebRequest

Kailash Chandra Behera | Friday, November 29, 2019

Introduction

This article discusses about the token-based Authentication or Bearer Token Authentication and provides code snippet to call Web API or Web Service having Bearer Authentication Token in client header using HttpWebRequest class.

Getting Started

Authentication is a vital process in system programming. It means verifying the user who is accessing the system. Today we are using modern devices that have different types of Apps or software and sometimes we directly access the website from browser. To access this application, we probably need to pass our credentials and these systems verify it. If you are valid user, then it will allow accessing the system otherwise not.

There are various types of authentication in .Net programming like Windows Authentication, Forms Authentication, Claim Based Authentication, Token-Based Authentication, etc. Today we will discuss Token Based Authentication in detail. Token-Based Authentication is not very different from other authentication mechanism but yes, it is more secure, more reliable, and makes your system loosely coupled. It will be a better choice to create REST API using token-based authentication if your API reached a broad range of devices like mobiles, tablets, and traditional desktops.

In token-based authentication, you pass your credentials (username and password) which go to the authentication server. The server verifies your credentials and if it is a valid user then it will return a signed token to the client system, which has expiration time. The client can store this token to locally using any mechanism like local storage, session storage, etc. If the client makes any other call to the server for data, then it does not need to pass its credentials every time. The client can directly pass the token to the server, which will be validated by the server and if the token is valid then you will able to access your data.

Before starting the demonstration let’s discuss the concept of the HttpWebRequest class. The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

Code Example


This code snippet covers only calling web API, it does not cover the getting token part through authentication with credential (username and password). This conducts only how to use HttpWebRequest class to call Web API or service with bearer token authentication.
 using System;  
 using System.Collections.Generic;  
 using System.IO;  
 using System.Linq;  
 using System.Net;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace BearerAuthentication  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       string api_token = "abc";  
       //initializing HttpWebRequest object   
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");  
       IWebProxy theProxy = request.Proxy;  
       if (theProxy != null)  
       {  
         theProxy.Credentials = CredentialCache.DefaultCredentials;  
       }  
       CookieContainer cookies = new CookieContainer();  
       request.UseDefaultCredentials = true;  
       request.CookieContainer = cookies;  
       request.ContentType = "application/json";  
       request.CookieContainer = cookies;  
       // write the "Authorization" header  
       request.Headers.Add("Authorization", "Basic " + api_token);  
       request.Method = "POST";  
       // get the response  
       //WebResponse response = request.GetResponse();  
       using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
       {  
         StreamReader reader = new StreamReader(response.GetResponseStream());  
         Console.Write(reader.ReadToEnd());  
       }  
     }  
   }  
 }  


Thanks