MVC 5, OAuth2, OWIN and Wireless Speakers

I was looking at ASP.NET MVC 5 in Visual Studio 2013. Here is step by step tutorial by Rick Anderson. Here is another great tutorial by Rick on how to add Oauth2  Sign-on.

Note: Go thru the above tutorial, generate the code and have it working. We will be referring to this code often. Should not take more than 10 min. Rick Anderson has done an awesome job.

Lots of code is generated by Visual studio scaffolding for you. However, while trying to understand what is going on, I felt like a man from 1940 looking at wireless speakers. You see that music is coming out of speakers but you don’t know how, where are the wires?

There are pieces of code which sort of make sense, but you don’t know who is calling them, what exactly they are doing. How all this code is wired. There are lots of behind the scene wiring happening.

Generated code, created more unanswered questions than the questions I got answered. I will make this post a step by step journey to completely understand MVC 5, Owin and Katana interaction. I will keep the repetition to minimum. Different pieces of puzzle are explained by many talented people, so I will be redirecting you to them. The only problem is all this writing is scattered in different places. Many articles are written by expert and they assume that you are already familiar with other piece of technology. However, this can be daunting for new developers who are left of their own to connect all the dots. This post is amalgamation of pieces and about solving the puzzle.

So without any further adieu, to completely understand the code and what is happening here is the laundry list of things you need to know:

Only after knowing all these pieces and thrashing on internet between many blogs, articles and stackoverflow slowly you will start completing the picture. I saw lot of frustration from new people to piece the story together. Same time many writers, Microsoft was trying their best to help you understand, they are often fighting the battle to keep things simple but still give you the full pictures. It is a fine balance to give you enough details but still keep things simple, as you can see in this article, i will be loosing the simplicity many times as i will get in to code which will muddy the water. But, hopefully you will be left with many pointers to investigate your own and slowly everything will fall in place.

Now, coming back to code. Here are the few questions, jumped at me while going thru the MVC5 application.

  • What is this attribute I see on one of the class.
    [assembly: OwinStartupAttribute(typeof(WindWood.Startup))]

    Note: windwood is my application name

  • There is a startup class, which has only one method called “Configuration”, what is it? Why it is called Configuration, can I call it something else?
  • Just uncommenting  app.UseGoogleAuthentication(); makes my google login work.  Magic!!! But how and why?
  • Whats the below code do, I don’t see any method call UseFacebookAuthentication on IAppBuilder. What the hell, am I hallucinating?

    app.UseFacebookAuthentication(
    appId: "25345345688543",
    appSecret: "1456785555658b24964345332224a02");
    
  • How the login details saved in DB.

You press F5, and every thing works fine. Kudos to Microsoft!  But If you are curious you will wonder how all this is wired up? So lets dig it up. First thing, I wanted to know what happens when you press F5. For that investigation, I have to step out of the MVC5 and get into Katana.

You can get the Katana code from github.  (Note: get the Katana code and have it open in another instance of visual studio. It is important to have the code in front of you to understand all the wiring.) As you know, OWIN is a standard interface between .NET web servers and web applications and Katana is a flexible set of components for building and hosting OWIN-based web applications.

We will go far from MVC but not too far (if you will go too far, then you may get lost in Http and IIS, TCP/IP and Network stack), we don’t want to get lost. So keeping this in mind, lets look at the MVC code. We found the following code in Startup.cs.

using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(WindWood.Startup))]
namespace WindWood{
  public partial class Startup {
      public void Configuration(IAppBuilder app){
           ConfigureAuth(app);
      }
}}

Hmmm .. .so what is it, and who calls it. You can look up and down in your project but you will never find it.  Actually the answer is hidden in Katana code.  Now, lets take  a look at the Katana, but before that lets talk about OWIN for a bit. OWIN is a specification that describes how components in a HTTP pipeline should communicate. The goal of OWIN is to decouple server and application. All the interaction between web server and application reduces to a very small set of types and single function signature known as AppFunc. AppFunc is defined in OwinAppContext.cs as


using AppFunc = Func<idictionary<string,object>, Task>;

AppFunc is a delegate which takes IDictionary and returns Task when it has finished processing. This IDictionary is a generic object bag, it carries all the states for application state, request and server state etc. This bag is passed from one component to another.

OWIN-compatible web server is referred to as a “host“, and an instance of an application delegate (described below) is referred to as an “Application“. In simple words, host invokes an application, and provids it with the key-value dictionary.

These two simple, a key-value dictionary and application delegate element enables this beautiful harmony between different framework and components to interoperate in an OWIN Pipeline.

So how does the Applications are provided to host? Here is another important actor of OWIN implementation, it is no more part of specification, but he is the glue between host and application. Application is provided to a host using the IAppBuilder interface.

public interface IAppBuilder{
       IDictionary<string, object> Properties { get; }
       object Build(Type returnType);
       IAppBuilder New();
       IAppBuilder Use(object middleware, params object[] args);
       }

Ok, so far we have seen IAppBuilder,  and understood every component in an OWIN-based application supplies an application delegate to a server. The components are then chained together into a pipeline into which an OWIN-based server pushes requests. Now, lets understand Katana on high level. Katana is a flexible set of components for building and hosting OWIN-based web applications . There are different stacks of  Katana and they consists of  following layers:

Host: The process that runs the application and can be anything from IIS or a standalone executable, to your own custom program. The host is responsible for startup, loading of other OWIN components and shutting down gracefully.

Server: Responsible for binding to a TCP port, constructing the environment dictionary and processing requests through an OWIN pipeline.

Middleware: The name given to all of the components that handle requests in an OWIN pipeline. It can range from a simple compression component to a complete framework such as ASP.NET Web API, though from the server’s perspective, it’s simply a component that exposes the application delegate.

Application: This is your code. Because Katana is not a replacement for ASP.NET but rather a new way to compose and host components, existing ASP.NET Web API and SignalR applications remain unchanged, as those frameworks can participate in an OWIN pipeline. In fact, for these kinds of applications, Katana components will be visible only in a small configuration class.

So, on a high level, we can guess that our Startup code is called from Katan. Let’s dig deep to see how Katana get started and how its code is wired up with out code. To see Katana stack implementation, lets start our journey from OwinHttpHandler in Katana code. OwinHttpHandler process request from System.Web as OWIN requests. When we press F5, IIS Express starts and an OwinHttpHandler is inserted in pipeline as HttpHandler. This is how an Owin Application looks.

owin

Remember. for Owin, application is just an instance of AppDelegate, which is defined as

Func<IDictionary<string, object>, Task>

Just for fun lets walk the trail till we reach to our Startup class which we seen in our application and Visual Studio was kind enough to write for us.

Owin hosts provides a factory method that accepts an AppDelegate as a parameter. In  ASP.NET an HttpHandler accepts this as a parameter.  Take a look at OwinHandler code

internal OwinHttpHandler(string pathBase, Func appAccessor)
   { _pathBase = pathBase;
     _appAccessor = appAccessor;
   }

However, the default OWIN Application get processed by this constructor

public OwinHttpHandler():
  this(Utils.NormalizePath(HttpRuntime.AppDomainAppVirtualPath), OwinApplication.Accessor){
 }

Notice here the  Accessor is a static method defined as follows in OwinApplication.cs


internal static<OwinAppContext> Accessor
{
 get { return () => _instance.Value; }
 set { _instance = new Lazy(value); }
}

Accessor is a delegate to a function, which means if you call Accessor.Invoke() you will get back a OwinAppContext, and _instance is defined as

private static Lazy _instance = new Lazy(OwinBuilder.Build)

Lazy initialization is used to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task. To prepare for lazy initialization, you create an instance of Lazy. The type argument of the Lazy object that you create specifies the type of the object that you want to initialize lazily. The constructor that you use to create the Lazy object determines the characteristics of the initialization. Lazy initialization occurs the first time the Lazy.Value property is accessed.

So, when _appAccessor is touched way up in HttpHandler BeginProcessing, the whole domino effect of Lazy initialization starts and OwinBuilder.Build static method is called to build an OwinAppContext.

internal static OwinAppContext Build(){
   Action<IAppBuilder> startup = GetAppStartup();
   return Build(startup);
   }

The above function in short returning a OwinAppContext. But in between, GetAppStartup is the method which in wiring your code with the OwinCode. Let’s see what happens in GetAppStartup, this method calls DefaultLoader Load method (DefaultLoader.cs), which in turn checks the following:

  1. If the web.config file has an appSetting with key=“owin:AppStartup”, the loader uses the setting value. The value must be a valid .NET-type name.
  2. If the assembly has the attribute [assembly: OwinStartup(typeof(MyStartup))], the loader will use the type specified in the attribute value.
  3. If neither of these conditions are true, the loader will scan the loaded assemblies looking for a type named Startup with a method that matches the signature void Configure(IAppBuilder app).

The above point 2, answers one of my first question about OwinStartup attribute.

[assembly: OwinStartupAttribute(typeof(WindWood.Startup))]

This Attribute is used to find  the entry point. The OwinStartup attribute overrides the naming convention.

Basically, GetAppStartup returns an Action<IAppBuilder> by making a delegate out of Startup type, and a method called “Configuration”. The delegate is made in DefaultLoader.cs, in case you are curious.

return builder => methodInfo.Invoke(instance, new[] { builder })

Here methodInfo is “Configuration” function which is taking an IAppBuilder as a parameter. This answer my another question, Configuration is a hardcoded string in Katana, so I must have a method name called “configuration”. This is using the naming convention. Katana looks for a class name Startup in namespace matching the assembly name or the global namespace and then look for a method called “Configuration”.  You can use appSetting element to override the naming convention. To use the some other friendly name you have to define an appSetting element in the configuration file.


 <add key="appStartup" value="type" />

Look here, to see an example of configuration file use.

Now, looking back up, you can see that startup is defined as follows.

Action startup = GetAppStartup();

This means startup is an Action which is pointing to my “Configuration” method, and ready to take a IAppBuilder parameter. The next line

return Build(startup)

builds a AppBuilder object, builds a dictionary of name-value pair and calls the startup by passing AppBuilder.

var builder = new AppBuilder();
 builder.Properties[Constants.OwinVersionKey] = Constants.OwinVersion;
 builder.Properties[Constants.HostTraceOutputKey] = TraceTextWriter.Instance;
 builder.Properties[Constants.HostAppNameKey] = HostingEnvironment.SiteName;
 builder.Properties[Constants.HostOnAppDisposingKey] = OwinApplication.ShutdownToken;
 builder.Properties[Constants.HostReferencedAssemblies] = new ReferencedAssembliesWrapper();
 builder.Properties[Constants.ServerCapabilitiesKey] = Capabilities;
 builder.Properties[Constants.SecurityDataProtectionProvider] = new MachineKeyDataProtectionProvider().ToOwinFunction();
 builder.SetLoggerFactory(new DiagnosticsLoggerFactory());
 startup(builder);

You can find the complete code snippet in OwinAppContext.cs file. So what is happening here exactly, let me explain again:

Startup(builder)

Startup is a delegate pointing to our configuration code, which is taking the AppBuilder as parameter. Call to Configure  setup up all the middleware we have defined in our ConfigureAuth.

After executing our “Configuration” function,  AppBuilder’s Build function is called and a pipeline entry point is set as follows:

AppFunc = (AppFunc)builder.Build(typeof(AppFunc));

Remember AppFunc is defined as follows:

using AppFunc = Func<idictionary<string, object="">, Task>;

By now, we have a OwinAppContext fully cooked, with all the middleware set and a AppFunc set to get things rolling. This nice OwinAppContext is given to OwinHttpHandler, which uses it in his BeginProcessRequest to get hold of AppFunc and call all the middlewares.

The Above startup(builder) actually kickstart things in our application. Now coming back to our code, we see Configuration is calling ConfigureAuth method.

public void ConfigureAuth(IAppBuilder app)
 {
 --snip --
 app.UseFacebookAuthentication(
 appId: "23423443",
 appSecret: "234232343212212434a02");

app.UseGoogleAuthentication();
 }

Remember, above code had another confusion for me, where is app.UseGoogleAuthentication comes from? I don’t see this code anywhere and app also does not have any method of this name. Ok, let’s go back to Katana, and there you will find that these are Extension methods on IAppBuilder. These extension methods internally calls “Use” method to populate the middleware.

Now once you understand all this, Looked at the code and seen how all this is wired together you should forget all about it. What you have to remember is that you need to have a class which is called Startup and should have a configuration method on it and takes an IAppBuilder as a parameter.

In my next post I will write how login information is getting saved in tables.

I hope, I am leaving you with some pointers to deepen your understanding of all the actors and how all this is connected together.  Please feel free to let me know if I missed something or how to improve it further.

________________________________________________________

Side note

You can run just Katana without IIS. For that Get Chocolotey. Chocolatey NuGet is a Machine Package Manager, somewhat like apt-get, but built with Windows in mind. After install Chocolotey, run the following from a command line

Cinst owinhost

Change your  Web, Start Action properties of project and give Katana as Start external program.

Start external program, specifies the full path of an alternative program that Visual Studio will run instead of starting the browser. The alternative program must have an .exe file-name extension. owinhost.exe, loads the HTTP listener upon launch and then begin listening on port 8080. The port is configurable on the command line. To invoke the application and send requests all you do is calling http://localhost:8080.

Check Glavs post (another) on this to know more and how to write a plain vanila Owin application.

_____________________________________________________________________________________

More reading :

Scott Allen blogs. Comment on Scotts Allen blog was inspiration for this post.

Howard Dierking articles on msdn. 

Dino Esposito article on MSDN

ASP.NET MVC Pipeline

Request handling pipeline poster

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s