Implementing Basic and JWT Token authentication with C# .NET


Authentication is probably the first thing you will encounter when building a secure Enterprise application and understanding how you can authenticate your application with different authentication protocols including third party authentication flows is really important. Whether you are building an app with ASP.NET, ASP.NET Core, WPF, UWP, Xamarin.Forms Xamarin Android, Xamarin iOS or .NET Core, all these frameworks provides
client side networking libraries managed under System.NET namespace. Among all the classes HttpClient has significant important. It can handle both HTTP and HTTPS connections. The beauty of this class is that it provides both hight level api and low level modification options to work with HTTP connections and you can make any modification  within the pipeline like handling HTTP message request/response, filtering, certificates, authorization and much more.

In a nutshell, over HTTP most of the times you will work with two kinds of authentication:
1) Basic (username/password based)
2) Token (access token and/or refresh token based)

Both of these authentication categories require that http request contains Authorization header. The format of the Authorization header in HTTP request is:

Authorzation: {schema} {parameter}

where schema is type of authentication being used and parameter is the value of the credentials/token.

Basic Authentication

 Basic authentication requires an http request to have an Authorization header key with value of Basic and base64 encoded string containing username and password separated by colon(:). Below here take a look at HTTP Request that has a Basic authentication header:

Fiddler Http Request composition

In case of Basic authentication, the value for schema is "Basic" and parameter is base64 representation of username and password separated by collon (":") like administrator:password

Note: In modern browsers and utilities you can also pass credential in url  and they will automatically convert it into authorization header where the credentials are base64 encoded string. The format is:

https://{username}:{password}@{hostname/}

Take a look at the url of the http request:
Fiddler Http Request with credentials in URL
Now look at the response about the request sent by fiddler, fiddler automatically converted url into Basic Authorization header when sending http request.
Http request header and JSON response from Windows IoT Server

Token Based Authentication

Token based authentication are widely used in OAuth, OpenId and access key based authentication. They also require that http request header contain Authorization key with value Bearer {Token} where Token is the value secret key of api token.

Lets see an example of usage of Token based authentication:

Token based Bearer authentication
Http reponse against bearer authentication

Basic authentication in C#

Lets see how to implement Basic authentication in C#. Initialize HttpClient class with default constructor. Get a byte array by passing string parameter containing username and password separated by colon (:) to static method GetBytes defined in Encoding class and overridden by ASCII class. Get an instance of AuthenticationHeaderValue class by calling its two parameter constructor passing in Basic as first parameter and credentials byte array as second parameter then assign the instance to Authorization property of DefaultRequest property under HttpClient instance (or simply htpClient.DefaultRequestHeaders.Authorization). Finally, call GetAsync instance method of httpClient object to get HttpResponseMessage. You can see authentication success result under HttpRespnseMessage response object's StatusCode enum received from GetAsync() method.

If you have an https website and using self-signed signed certificate checkout code here on how to ignore self-signed certificated exceptions.

Token Authentication in C#

Lets see how to implement Bearer authentication in C#. As discussed earlier, Bearer Authentication is token based where you will receive an access token from either OAuth2.0 or OpenId endpoint or some Auth providers might directly provide you an API Secret Key which is a token.. Once you have the JWT token, your simply need to pass it on the Authorization header with Bearer scheme (no need to convert token to base64 encoded string).

In C#, initialize HttpClient class with default constructor. Get an instance of AuthenticationHeaderValue class by calling its two parameter constructor passing in Bearer as first parameter and token as second parameter then assign the instance to Authorization property of DefaultRequest property under HttpClient instance (or simply htpClient.DefaultRequestHeaders.Authorization). Finally, call GetAsync instance method of httpClient object to get HttpResponseMessage. You can see authentication success result under HttpRespnseMessage response object's StatusCode enum received from GetAsync() method.

If you have an https website and using self-signed signed certificate checkout code here on how to ignore self-signed certificated exceptions.

Just a last note, if you have an https website and get certificate related exception when running the code above you then register a certificate validator callback to return true.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

Comments

  1. FL Studio Crack is the latest powerful music production tool. ... Firstly, download the FL Studio Crack from the below setup button. FL Studio Crack Version

    ReplyDelete
  2. I just wanted to let you know that you are on my mind every single day of the year, especially today on Christmas. I hope you have the biggest smile today Christmas Wishes For Loved Ones

    ReplyDelete

Post a Comment

Popular posts from this blog

Setting up Free Custom Domain on Microsoft Azure Web App Service

.NET Core 3 officially comes to Windows IoT Core

Setting up CI and CD pipeline in Azure DevOps for ASP.NET Core and Azure Web Apps

Microsoft Azure DevOps : A Complete CI & CD solution in the cloud

Microsoft Azure Blob Storage - Managing Blobs and storage containers from C#

Xamrin Android Push Notification using Firebase Cloud Messaging

Securing Powershell Scripts with Code-Signing Certificate

Understanding Powershell ExecutionPolicy and securing Powershell CmdLets/Scripts with Code-Signing Certificate

Fundamental of Powershell Scripting