Saturday, 15 September 2018

Intercept the HttpRequest to Create a custom authentication with owin middleware in WebApi

In this post we are going to see how to create a custom authentication with owin middle in webapi. OwinMiddleware will intercept the HttpRequest for do a authentication for every request.To do this first we have the list out the requirements for the authentication, we are going to do the pin based authentication by sending the following header in the request with pin value "x-token-auth"

sample header:
"x-token-auth": token|50003

we are going to send this header with above value if the value is less than 10000 than we have to return UnAuthorized. let we see the implementation.

1. Create the class by derving it from OwinMiddleware.
2. Then override the Invoke method.
3. Check the pin sending in the headers inside the Invoke method
4. use this middleware in the startup.cs


1. create a class PinBasedAuthenticationMiddleware 
*****************************************************


using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;

namespace WebApplication4.Authentication
{
    public class PinBasedAuthenticationMiddleware : OwinMiddleware
    {
        public PinBasedAuthenticationMiddleware(OwinMiddleware next) : base(next)
        {
        }

        public override async Task Invoke(IOwinContext context)
        {
            bool authorised = IsAuthorised(context.Request.Headers);
            if (authorised)
            {
                IEnumerable<Claim> claimCollection = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier,"123456"),
                    new Claim(ClaimTypes.Country, "India"),
                    new Claim(ClaimTypes.Gender,"Male"),
                    new Claim(ClaimTypes.Email,"test@gmail.com"),
                    new Claim(ClaimTypes.Role, "SA"),
                    new Claim(ClaimTypes.Sid,Guid.NewGuid().ToString())
                };
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "Pin_Based");
                IPrincipal principal = new ClaimsPrincipal(claimsIdentity);
                context.Request.User = principal;
                await Next.Invoke(context);
            }
            else
            {
                context.Response.ReasonPhrase = "UnAuthorized";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }           
        }



        private bool IsAuthorised(IHeaderDictionary requestHeaders)
        {
            string[] pinValues;
         bool pinHeaderPresent = requestHeaders.TryGetValue("x-token-auth", out pinValues);
            if (pinHeaderPresent)
            {
                string[] valuesInHeader = pinValues.ToList()[0].Split(new char[] { '|' }, 
                                          StringSplitOptions.RemoveEmptyEntries);
                if (valuesInHeader.Length == 2)
                {
                    int pin;
                    if (int.TryParse(valuesInHeader[1], out pin))
                    {
                        if (pin >= 10000)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

    }

}


2. Use this middleware in startup.cs
**********************************

using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication4.Authentication;

namespace WebApplication4
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Use<PinBasedAuthenticationMiddleware>();
        }       
    }

}


Controller:
****************
public class ValuesController : ApiController
    {
        // GET api/values
        public IHttpActionResult Get()
        {           
            var data = new string[] { "value1", "value2" };
            return Ok(data);
        }

        // GET api/values/5
        public string Get(int id)
        {
            var data = "Rajesh";
            return data;
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
       
    }



3. Make a call to the endpoint with pin value less than 10000 using postman will result in UnAuthorized





4. Make a call to the endpoint with pin value greater than 10000 using postman will result in success authentication




From this post you can learn how to intercept the HttpRequest to create a custom authentication with owin middleware in webapi.


No comments:

Post a Comment