Skip to main content

How to do JWT Authentication using a DelegateHandler in WEBAPI



According to AuthO, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.


In using jwt, the information in the token, is the only thing required to authenticate a user. so our main here is to validate the information in the token and convert jwt to IPrincipal object. Iprincipal object, according to msdn, simply means the functionality of a principal object, what then is a principal object, A principal object represents the security context of the user on whose behalf the code is running, including that user's identity (IIdentity) and any roles to which they belong.
To make this JWT authentication to work, we must utilize a message handler, a message handler is simply a class that receives an HTTP request and returns an HTTP response. Instead of implementing our own message handler, we are going to be using an existing nugget package, JWTAuthForWepAPI.


The information structure in JWT token it’s as follows
             1.Header: JSON format which is encoded as a base64
  2. Claims: JSON format which is encoded as a base64.
3. Signature: Created and signed based on Header and Claims which is   encoded  as a base64.


Setting up JWTAuthForWepAPI


JWTAuthForWepAPI is a delegatingHandler that creates a  new ClaimsPrincipal based on incoming token and assigned it to the current thread. This delegateHanlder will make the authentication to operate at the level of HTTP message rather than controller and actions.


Get JWTAuthForWepAPI from Nugget. Then proceed to add the following to your webconfig file.


<section name="JwtAuthForWebAPI"
type="JwtAuthForWebAPI.JwtAuthForWebApiConfigurationSection"/>

<JwtAuthForWebAPI
AllowedAudience=”http://website url”
Issuer="COPR"
SymmetricKey="95896GREJBA3B06519C8DDDBC80JHI80553"; />


To generate the needed token you can use System.IdentityModel.Tokens.Jwt from MS or  HMACSHA256 with SymmetricKey or may be any other provider that you desire.


Configuring MessageHandler


The next steps is to add codes that configure the associated messagehandler. A message handler is simply a class that receives an HTTP request and returns an HTTP response.


var tokenBuilder = new SecurityTokenBuilder();
var configReader = new ConfigurationReader();

var jwtHandlerSharedKey = new JwtAuthenticationMessageHandler
{
   AllowedAudience = configReader.AllowedAudience,
   Issuer = configReader.Issuer,
   SigningToken = tokenBuilder.CreateFromKey(configReader.SymmetricKey),
};

config.MessageHandlers.Add(jwtHandlerSharedKey);


At this point our service can accept json web token, signed with a particular symmetric key.


Creating a valid Jwt
The code listed below will create a valid jwt that will be available  for authentication.


public const string Secret = "95896GREJBA3B06519C8DDDBC80JHI80553"; // your symmetric

public static string GetToken(string username, int lifetime = 30)
   {
       var symmetricKey = Convert.FromBase64String(Secret);
       var tokenHandler = new JwtSecurityTokenHandler();

       var today = DateTime.UtcNow;
       var tokenDescriptor = new SecurityTokenDescriptor
       {
           Subject = new ClaimsIdentity(new[]
                   {
                       new Claim(ClaimTypes.Name, username)
                   }),
           TokenIssuerName = configReader.Issuer,
           AppliesToAddress = configReader.AllowedAudience,
           Expires = today.AddMinutes(Convert.ToInt32(lifetime)),

           SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
       };

       var stoken = tokenHandler.CreateToken(tokenDescriptor);
       var token = tokenHandler.WriteToken(stoken);

       return token;
   }


Because the jwt based handler was configured and added to the ASP.NET WEB API message handler collection , it can now accept JWT authentication.

Comments

Popular posts from this blog

How to implement RESTful API Versioning in ASP.NET Web API 2 using IHttpRouteConstraint

The only thing constant in life is change, and that is proved everyday in our industry, API’s are cool to extend the functionality of your application and expose it to other developers. The cool thing about IT and software, it’s that things changes quite rapidly and so it’s the technology, hence technology can change and the needs of your organisation can change, hence in order to keep serving this evolving needs and keep been relevant, your api might need to change also. Small changes can be accommodated within the initial version, but changes that will risked breaking the existing code, will required the need for versioning.

Implementing a custom IHttpRouteConstraint

According to msdn, a IHttpRouteConstraint simply Represents a base class route constraint. What then is a route constraint? A route constraint simply gets or sets a dictionary of expressions that specify valid values for a URL parameter.

publicclassApiVersionRouteConstraint : IHttpRouteConstraint
  {

publicApiVersionRouteCo…

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…

How to do partial update for HTTP APIs in ASP.NET CORE MVC with JSON Patch

JSON Patch is a format for describing changes to a JSON document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the HTTP PATCH method, it allows partial updates for HTTP APIs in a standards compliant way. A JSON Patch document is just a JSON file containing an array of patch operations. The patch operations supported by JSON Patch are “add”, “remove”, “replace”, “move”, “copy” and “test”. The operations are applied in order: if any of them fail then the whole patch operation should abort.
The JSON Patch supports the following operations:
Add - Adds a value to an object or inserts it into an array.Remove -  Removes a value from an object or array. Replace - Replaces a value. Equivalent to a “remove” followed by an “add”. Copy - Copy a value from one location to another within the JSON document. Both from and path are JSON Pointers. Move - Move a value from one location to the other. Both from and path are JSON Pointers. Test - Te…