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 about 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 to broad range of devices like mobiles, tablets and traditional desktops.
Before starting demonstration let’s discuss about the concept of 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
Kailash Chandra Behera
No comments:
Post a Comment