Recently I worked on a project which is used Oauth as authentication mechanism. In this project we need to implement a custom authentication mechanism as well to validate some users. While I am researching on this I found Owin and Katana offers a flexible pipeline for external authentication with existing providers for authentication by Google, Facebook, Twitter and more. Good news for me it is also possible to write your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.
In this article I am going to explain how we can develop your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.
Normally Katana middleware is made up of 4 classes.
- The main MyCustomAuthenticationMiddleware class.
- The internal MyCustomAuthenticationHandler class doing the actual work.
- A MyCustomAuthenticationOptions class for handling settings.
- An extension method in MyCustomAuthenticationExtensions for easy setup of the middleware by the client application.
Any middleware will need some kind of configurations. It is stored in an options class. To work with the Katana base classes, it must inherit AuthenticationOptions class in Microsoft.Owin.Security namespace, which contains some mandatory options that are used by the framework. In my class I am going to use authentication type option only.
MyCustomAuthenticationHandler class (Inside MyCustomAuthConfig.cs)
This is where a real handler would inspect the incoming authentication ticket from the external authentication server. My Custom middleware just creates an identity with the values from the configuration (See custom middleware below).
The middleware is a factory that creates instances of the handler that does the actual work of processing requests. Only one instance of the middleware is instantiated. The middleware constructor checks the configuration in the options class and if certain properties are null, it adds some defaults that are dependent on the previous middlewares in the pipeline.
The IAppBuilder.Use method takes an object as the first parameter, which has the advantage that a middleware won’t need to have a reference to a particular assembly containing a specific middleware interface. But using an untyped object makes it more confusing for callers. This is where the extension method comes into the play, it makes it easy to register the middleware in the Owin pipeline.
Finally my MyCustomAuthConfig look like this.
In your startup class you need to call the MyCustomAuthConfig.SetupVerification(app) method to apply your implementation.