Sign Post

Branching Pipelines with OWIN

Branching pipelines with OWIN allow for several different request pipelines to be used as needed depending on a determining factor. This factor is most often a Hostname but it could be any sort of toggle.

An example might be authentication. Your system might need to allow for different authentication mechanisms for different users. The set up for authentication happens once when the app is built-in IIS for the first time and can be found in Startup.Auth. At this point the application hasn’t even received any requests so how is it supposed to know what authentication system to use?

This is where OWIN and mapWhen() come in useful. By using “map when”, you set up multiple pipelines on application start and cache them. The correct pipeline will then be used based on the conditional check supplied.

public partial class Startup
{
    public static void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(SecurityContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager
            (ApplicationUserManager.Create);

        app.MapWhen(ctx => ClientUsesAAD(), config =>
        {
            ConfigureAzureActiveDirectory(config);
        });

        app.MapWhen(ctx => ClientUsesCookies(), config =>
        {
            ConfigureCookieAuthentication(config);
        });

        app.MapWhen(ctx => ClientUsesSSO(), config =>
        {
            ConfigureCookieAuthentication(config);
            ConfigureSSO(config);
        });
    }
}

In the example above, you can see that depending on what Authentication method the client uses, a different pipeline can be used.

Some things to remember though!

  • The pipelines are set up once when the application starts for the first time. They are then cached. Because of this, any configuration that is to be used has to be available when the application starts.
  • The conditional checks are run per request. This means you can check the HTTPContext and other things if you need to. However as these statements will be run on every request, you need to keep their efficiency in mind else you could end up slowing down your application.

This isn’t limited to authentication. Any application configuration done in startup files can be branched like this.