title: How can I replace HttpContext.User in ASP.NET Core after Authorization?
body: <p>I have a custom user class <code>MyPrincipal</code> with some custom properties, with which I want to replace the authenticated <code>ClaimsPrincipal</code>, e.g. <code>HttpContext.User</code></p>
  
  <p>I have added a custom middleware:</p>
  
  <pre><code>public class MyMiddleware {
    private readonly RequestDelegate next;
  
    public MyMiddleware(RequestDelegate next) {
      this.next = next;
    }
  
    public async Task Invoke(HttpContext context) {
      if (context.User.IsAuthenticated) {
        context.User = new MyPrincipal(context.User);
      }
      await next(context);
    }
  }
  </code></pre>
  
  <p>I have registered the middleware to run after authentication, but before MVC in <code>Startup.cs</code>:</p>
  
  <pre><code>public void Configure(IApplicationBuilder app) {
    app.UseAuthentication();
    app.UseMiddleware&lt;MyMiddleware()&gt;;
    app.UseMvcWithDefaultRoute();
  }
  </code></pre>
  
  <p>In my <code>_Layout.cshtml</code> I want to use a custom property from my <code>MyPrincipal</code>:</p>
  
  <pre><code>...
  @if (User is MyPrincipal) {
    &lt;do stuff&gt;
  }
  ...
  </code></pre>
  
  <p>So far so good, the user is recognized as <code>MyPrincipal</code>.</p>
  
  <p><strong>But when I add a global Authorization policy:</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services) {
    services.AddMvc(options =&gt; {
      var policy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
          .RequireAuthenticatedUser()
          .Build();
      options.Filters.Add(new AuthorizeFilter(policy));
    });
  }
  </code></pre>
  
  <p>Suddenly, the <code>User</code> in <code>_Layout</code> is just a <code>ClaimsPrincipal</code>.</p>
  
  <p><strong>How can I either stop MVC from replacing my principal, or hook into the pipeline after the authorization policy has completed?</strong></p>
  
  <p>P.S. I am using the ASP.NET Core 2.0 Preview 2, in case it matters.</p>