Monday 11 February 2019

Using the OwinMiddleware in AspNet Core (or) use IAppBuilder in IApplicationBuilder

In this post we are going to see how to use the OwinMiddleware in Asp.net Core or use the IAppBuilder in IApplicationBuilder.

First we will see the custom OwinMiddleware which will authenticate the user in Web Api Request.

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;
        }
        
    }

Now we will see how to use this middleware in Asp.Net Core, Normally we cant do this straight away. because in Asp Net core it is using the IApplicationBuilder, but to configure the owin middleware we need the IAppBuilder.

Let we do a Extension Methods which will do this.
First install the following package in application install package Microsoft.AspNetCore.App
to use the UseOwin method

internal static class ApplicationBuilderExtension {
    public static IApplicationBuilder UseOwinMiddleware(
    this IApplicationBuilder coreApp,
    Action<IAppBuilder> configuration) {
        return coreApp.UseOwin(setup => setup(next => {
            AppBuilder owinBuilder = new AppBuilder();
            IApplicationLifetime coreLifeTime = 
                        (IApplicationLifetime)coreApp.ApplicationServices
                            .GetService(typeof(IApplicationLifetime));
            AppProperties owinProp = new AppProperties(owinBuilder.Properties);
            owinProp.OnAppDisposing = coreLifeTime?.ApplicationStopping ?? 
                                               CancellationToken.None;
            owinProp.DefaultApp = next;
            configuration(owinBuilder);
            return owinBuilder.Build<Func<IDictionary<string, object>, Task>();
        }));

    }
}


How to use this extension method in asp.net core, let we see that.

public class Startup {
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
  /* install package Microsoft.AspNetCore.App */
  app.UseOwinMiddleware((build) => {
           build.MapWhen((ctx) => {
                          return ctx.Request.Headers.ContainsKey("rash");
                         },
                         (appbuilder) => {
                           appbuilder.Use<PinBasedAuthenticationMiddleware>();
                         });
            });
 }
}


I am applying a middleware based on condition whenever the request contains the headers "rajesh" following middleware will be apply, this middleware will authenticate the request.


From this post you can learn how to use the OwinMiddleware in Asp.net Core. or use IAppBuilder in IApplicationBuilder.