title: Get authenticated user from Middleware class in Blazor app
body: <p>I have a server sided Blazor app. Every user must be authenticated when he wants to visit a page. For this the user is redirected to an "identity server" login page. When the user logs in with the correct credentials, he is then redirected back to the Blazor app.</p>
  
  <p>I have setup my Blazor app with <code>CascadingAuthenticationState</code>, so that I can access the <code>User</code> object and its claims inside my Blazor pages.</p>
  
  <p>This goes something like this inside a component:</p>
  
  <pre><code>[CascadingParameter]
  private Task&lt;AuthenticationState&gt; AuthenticationStateTask { get; set; }
  ...
  ... 
  var authState = await AuthenticationStateTask;
  var claims = authState.User.Claims; // Works fine.
  </code></pre>
  
  <p>When I do it like this I have access to the users claims.</p>
  
  <p><strong>So far so good.</strong></p>
  
  <p>But I also have a <em>middleware</em> class where I need to access the user claims.</p>
  
  <pre><code>public async Task InvokeAsync(HttpContext context)
  {
      if (context?.User?.Claims != null &amp;&amp; context.User.Claims.Any())
      {
          Console.WriteLine("aaa");
      }
  
      // Call the next delegate/middleware in the pipeline
      await _next(context);
  }
  </code></pre>
  
  <p>But for some reason the <code>User</code> claims are always empty.</p>
  
  <p>Why is the <code>User.Claims</code> object from inside my Blazor component filled with all the claims, but are they empty when I access them through the <code>HttpContext</code> object?</p>