title: HttpContext.User NullReferenceException only on deployed server
body: <p>I am using formsauthentication on my MVC project and when testing locally using the Visual Studio Development Server everything works as expected. Once deployed to IIS 7.5 the <code>HTTPContext.User</code> is causing <code>NullReferenceException</code>s.</p>
  <p>Both Dev and Prod machines are using the same SQL db (at the moment - this will change post-deployment of course) so I know it is not a problem with the DB or data within.</p>
  <p>This must be a setting in IIS or my web.config but I cannot find it.
  I've tried various changes to my web.config(from suggestions I've found around SE), here is part of my web.config for the current implementation:</p>
  <pre><code>&lt;appSettings&gt;
      &lt;add key=&quot;autoFormsAuthentication&quot; value=&quot;true&quot; /&gt;
      &lt;add key=&quot;enableSimpleMembership&quot; value=&quot;false&quot; /&gt;
      &lt;add key=&quot;webpages:Version&quot; value=&quot;2.0.0.0&quot; /&gt;
      &lt;add key=&quot;webpages:Enabled&quot; value=&quot;false&quot; /&gt;
      &lt;add key=&quot;PreserveLoginUrl&quot; value=&quot;true&quot; /&gt;
      &lt;add key=&quot;ClientValidationEnabled&quot; value=&quot;true&quot; /&gt;
  
  ****Snip****
  
  &lt;system.web&gt;
      &lt;httpRuntime targetFramework=&quot;4.5&quot; /&gt;
      &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.5&quot; /&gt;
      &lt;authentication mode=&quot;Forms&quot;&gt;
        &lt;forms loginUrl=&quot;~/Account/Login&quot; timeout=&quot;2880&quot; cookieless=&quot;UseCookies&quot;/&gt;
      &lt;/authentication&gt;
      &lt;pages&gt;
        &lt;namespaces&gt;
          &lt;add namespace=&quot;System.Web.Helpers&quot; /&gt;
          &lt;add namespace=&quot;System.Web.Mvc&quot; /&gt;
          &lt;add namespace=&quot;System.Web.Mvc.Ajax&quot; /&gt;
          &lt;add namespace=&quot;System.Web.Mvc.Html&quot; /&gt;
          &lt;add namespace=&quot;System.Web.Optimization&quot; /&gt;
          &lt;add namespace=&quot;System.Web.Routing&quot; /&gt;
          &lt;add namespace=&quot;System.Web.WebPages&quot; /&gt;
          &lt;add namespace=&quot;ProjectSquid.WebUI.HTMLHelpers&quot; /&gt;
        &lt;/namespaces&gt;
      &lt;/pages&gt;
      &lt;roleManager enabled=&quot;true&quot; defaultProvider=&quot;CustomRoleProvider&quot;&gt;
        &lt;providers&gt;
          &lt;clear /&gt;
          &lt;add name=&quot;CustomRoleProvider&quot; 
               type=&quot;Project.Domain.Filters.CustomRoleProvider&quot;
               connectionStringName=&quot;EFDbContext&quot;
               enablePasswordRetrieval=&quot;false&quot;
               cacheRolesInCookie=&quot;true&quot;/&gt;
        &lt;/providers&gt;
      &lt;/roleManager&gt;
      &lt;membership defaultProvider=&quot;SimpleMembershipProvider&quot;&gt;
        &lt;providers&gt;
          &lt;clear /&gt;
          &lt;add name=&quot;SimpleMembershipProvider&quot; type=&quot;WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData&quot; /&gt;
        &lt;/providers&gt;
      &lt;/membership&gt;
      &lt;sessionState mode=&quot;InProc&quot; customProvider=&quot;DefaultSessionProvider&quot;&gt;
        &lt;providers&gt;
          &lt;add name=&quot;DefaultSessionProvider&quot; type=&quot;System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot; connectionStringName=&quot;EFDbContext&quot; /&gt;
        &lt;/providers&gt;
      &lt;/sessionState&gt;
  
  &lt;system.webServer&gt;
      &lt;httpProtocol&gt;
        &lt;customHeaders&gt;
          &lt;add name=&quot;X-UA-Compatible&quot; value=&quot;IE=9&quot; /&gt;
        &lt;/customHeaders&gt;
      &lt;/httpProtocol&gt;
      &lt;validation validateIntegratedModeConfiguration=&quot;false&quot; /&gt;
      &lt;handlers&gt;
        &lt;remove name=&quot;ExtensionlessUrlHandler-ISAPI-4.0_32bit&quot; /&gt;
        &lt;remove name=&quot;ExtensionlessUrlHandler-ISAPI-4.0_64bit&quot; /&gt;
        &lt;remove name=&quot;ExtensionlessUrlHandler-Integrated-4.0&quot; /&gt;
        &lt;add name=&quot;ExtensionlessUrlHandler-ISAPI-4.0_32bit&quot; path=&quot;*.&quot; verb=&quot;GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS&quot; modules=&quot;IsapiModule&quot; scriptProcessor=&quot;%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll&quot; preCondition=&quot;classicMode,runtimeVersionv4.0,bitness32&quot; responseBufferLimit=&quot;0&quot; /&gt;
        &lt;add name=&quot;ExtensionlessUrlHandler-ISAPI-4.0_64bit&quot; path=&quot;*.&quot; verb=&quot;GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS&quot; modules=&quot;IsapiModule&quot; scriptProcessor=&quot;%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll&quot; preCondition=&quot;classicMode,runtimeVersionv4.0,bitness64&quot; responseBufferLimit=&quot;0&quot; /&gt;
        &lt;add name=&quot;ExtensionlessUrlHandler-Integrated-4.0&quot; path=&quot;*.&quot; verb=&quot;GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS&quot; type=&quot;System.Web.Handlers.TransferRequestHandler&quot; preCondition=&quot;integratedMode,runtimeVersionv4.0&quot; /&gt;
      &lt;/handlers&gt;
      &lt;modules runAllManagedModulesForAllRequests=&quot;false&quot;&gt;
        
        &lt;remove name=&quot;FormsAuthentication&quot; /&gt;
        &lt;remove name=&quot;DefaultAuthentication&quot; /&gt;
        &lt;add name=&quot;FormsAuthentication&quot; type=&quot;System.Web.Security.FormsAuthenticationModule&quot; preCondition=&quot;&quot; /&gt;
        &lt;add name=&quot;DefaultAuthentication&quot; type=&quot;System.Web.Security.DefaultAuthenticationModule&quot; preCondition=&quot;&quot; /&gt;
        
        &lt;remove name=&quot;UrlRoutingModule-4.0&quot;/&gt;
        &lt;add name=&quot;UrlRoutingModule-4.0&quot; type=&quot;System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&quot; preCondition=&quot;&quot; /&gt;
        &lt;add name=&quot;ErrorLog&quot; type=&quot;Elmah.ErrorLogModule, Elmah&quot; preCondition=&quot;managedHandler&quot; /&gt;
        &lt;add name=&quot;ErrorMail&quot; type=&quot;Elmah.ErrorMailModule, Elmah&quot; preCondition=&quot;managedHandler&quot; /&gt;
        &lt;add name=&quot;ErrorFilter&quot; type=&quot;Elmah.ErrorFilterModule, Elmah&quot; preCondition=&quot;managedHandler&quot; /&gt;
      &lt;/modules&gt;
    &lt;/system.webServer&gt;
  </code></pre>
  <p>What could cause <code>HttpContext.User</code> to differ from the VS Development Server and the IIS 7.5 implementation?</p>
  <p><strong>EDIT:</strong></p>
  <p><code>HttpContext</code> is fed through the inherited BaseController:</p>
  <pre><code>protected virtual new CustomPrincipal User
  {
      get { return HttpContext.User == null? null : HttpContext.User as CustomPrincipal; }
  }
  
  public new HttpContextBase HttpContext
  {
      get
      {
          return ControllerContext == null ? null : ControllerContext.HttpContext;
      }
  }
  </code></pre>
  <p>The cookie isn't created until the PostAuthenticationRequest:</p>
  <pre><code> public void MvcApplication_PostAuthenticationRequest(object sender, EventArgs e)
  {
  
      var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
      if (authCookie != null)
      {
  
          string encTicket = authCookie.Value;
          if (!String.IsNullOrEmpty(encTicket))
          {
              
              var ticket = FormsAuthentication.Decrypt(encTicket);
              var id = new UserIdentity(ticket);
              string[] userRole = Roles.GetRolesForUser(id.Name);
              var prin = new CustomPrincipal(id);
              HttpContext.Current.User = prin;
              Thread.CurrentPrincipal = prin;
          }
      }
  }
  </code></pre>
  <p>The authentication itself appears to be working fine as the function causing the exception starts with <code>[Authorize]</code> and successfully begins executing but fails as <code>null</code> when it reaches the first User reference:</p>
  <pre><code>int userT = User.Team.TeamId;
  </code></pre>
  <p>In this context the User being <code>CustomPrincipal</code> <code>BaseController.User</code>.</p>
  <p><strong>EDIT2:</strong></p>
  <pre><code>&lt;authentication mode=&quot;Forms&quot;&gt;
    &lt;forms loginUrl=&quot;~/Account/Login&quot; timeout=&quot;2880&quot; 
           cookieless=&quot;UseCookies&quot;
           name=&quot;.ASPXAUTH&quot;
           protection=&quot;All&quot;
           slidingExpiration=&quot;true&quot;/&gt;
  &lt;/authentication&gt;
  </code></pre>
  <p><strong>EDIT3</strong></p>
  <p>Custom <code>IIdentity</code>:</p>
  <pre><code> [Serializable]
      public class UserIdentity : MarshalByRefObject, IIdentity
      {
          private readonly FormsAuthenticationTicket _ticket;
  
  
          public UserIdentity(FormsAuthenticationTicket ticket)
          {
              _ticket = ticket;
          }
  
          public string AuthenticationType
          {
              get { return &quot;Custom&quot;; }
          }
  
          public bool IsAuthenticated
          {
              get { return !string.IsNullOrEmpty(this.Name); }
          }
  
          public string Name
          {
              get { return _ticket.Name; }
          }
  
          public string UserId
          {
              get { return _ticket.UserData; }
          }
  
          public bool IsInRole(string Role)
          {
              return Roles.IsUserInRole(Role);
          }
  
          public IIdentity Identity
          {
              get { return this; }
          }
  
  
  public void GetObjectData(SerializationInfo info, StreamingContext context)
      {
          if (context.State == StreamingContextStates.CrossAppDomain)
          {
              GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
              info.SetType(gIdent.GetType());
  
              System.Reflection.MemberInfo[] serializableMembers;
              object[] serializableValues;
  
              serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
              serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);
  
              for (int i = 0; i &lt; serializableMembers.Length; i++)
              {
                  info.AddValue(serializableMembers[i].Name, serializableValues[i]);
              }
          }
          else
          {
              throw new InvalidOperationException(&quot;Serialization not supported&quot;);
          }
      }
  </code></pre>
  <p>Custom <code>IPrincipal</code>:</p>
  <pre><code>interface ICustomPrincipal : IPrincipal
  {
      int Id { get; set; }
      string Name { get; set; }
      string Role { get; set; }
  }
  
  public class CustomPrincipal : IPrincipal
  {
      public CustomPrincipal(UserIdentity identity)
      {
          this.Identity = identity;
      }
  
      public IIdentity Identity { get; private set; }
  </code></pre>