title: How to handle authentication in multi-tenant MVC 5 app
body: <p>I am trying to build a multi-tenant mvc 5 site that uses a single database and differentiates the tenants by schema in Sql Server.
  I started with the default Mvc 5 template and updated the ApplicationDBContext that is provided to take a string specifying the schema to use for that tenant like so.</p>
  
  <pre><code>public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt;
  {
      private string _tenantSchema;
      public ApplicationDbContext(string tenantSchema)
          : base("Dev", throwIfV1Schema: false)
      {
          _tenantSchema = tenantSchema;
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.HasDefaultSchema(_tenantSchema);
          base.OnModelCreating(modelBuilder);
      }
  
      public static ApplicationDbContext Create(string tenantSchema)
      {
          return new ApplicationDbContext(tenantSchema);
      }
  }
  </code></pre>
  
  <p>And then in the App_Start\IdentityConfig.cs I updated the Create Method of the ApplicationUserClass to use the first part of the Request.Host value to use as the tenantSchema like so</p>
  
  <pre><code> public static ApplicationUserManager Create(IdentityFactoryOptions&lt;ApplicationUserManager&gt; options, IOwinContext context) 
      {
          var tenantSchema = context.Request.Host.Value.Split('.')[0];
          var ctx = new ApplicationDbContext(tenantSchema);
  
          var userStore = new UserStore&lt;ApplicationUser&gt;(ctx);
          var manager = new ApplicationUserManager(userStore);
  </code></pre>
  
  <p>so if I were to log into site1.mysite.dev it would authenticate against the tables in the site1 schema is sql server. </p>
  
  <p>When I start the site and access it using the site1 sub domain it correctly uses the site1 Schema to authenticate me. But then if I change url in the browser address bar and log in again it still validates against the site1 schema.</p>
  
  <p>How can I configure the app to use to correct schema to check authentication for each request? </p>