title: Server-side Blazor Autorize Attribute is not working
body: <p>I have a problem, the authorize attribute is not working on a page, using Server-side Blazor. </p>
  
  <p>I have followed the following docs: <a href="https://docs.microsoft.com/fr-fr/aspnet/core/security/blazor/?view=aspnetcore-3.1" rel="nofollow noreferrer">https://docs.microsoft.com/fr-fr/aspnet/core/security/blazor/?view=aspnetcore-3.1</a></p>
  
  <p>And <a href="https://gunnarpeipman.com/client-side-blazor-authorizeview/" rel="nofollow noreferrer">https://gunnarpeipman.com/client-side-blazor-authorizeview/</a>, which is a bit outdated.</p>
  
  <p>So here's the custom provider:</p>
  
  <pre><code>using Microsoft.AspNetCore.Components.Authorization;
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Security.Claims;
  using System.Threading.Tasks;
  
  namespace CustomAuth
  {
      public class MyAuthenticationStateProvider : AuthenticationStateProvider
      {
          public static bool IsAuthenticated { get; set; }
          public static bool IsAuthenticating { get; set; }
  
          public override async Task&lt;AuthenticationState&gt; GetAuthenticationStateAsync()
          {
              ClaimsIdentity identity;
  
              if (IsAuthenticating)
              {
                  return null;
              }
              else if (IsAuthenticated)
              {
                  identity = new ClaimsIdentity(new List&lt;Claim&gt;
                          {
                              new Claim(ClaimTypes.Name, "TestUser")
  
                          }, "WebApiAuth");
              }
              else
              {
                  identity = new ClaimsIdentity();
              }
  
              return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
          }
  
          public void NotifyAuthenticationStateChanged()
          {
              NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
          }
      }
  }
  </code></pre>
  
  <p>In my login.razor:</p>
  
  <pre><code>@page "/Login"
  @using CustomAuth
  
  
  @inject MyAuthenticationStateProvider MyAuthStateProvider
  
  
  &lt;h1&gt;Hello, world!&lt;/h1&gt;
  
  Welcome to your new app.
  
  &lt;SurveyPrompt Title="How is Blazor working for you?" /&gt;
  
  &lt;button @onclick="@(() =&gt; UpdateAuthentication(true))"&gt;
      Set authenticated
  &lt;/button&gt;
  &lt;button @onclick="@(() =&gt; UpdateAuthentication(false))"&gt;
      Set anonymous
  &lt;/button&gt;
  &lt;button @onclick="@(() =&gt; UpdateAuthentication(null))"&gt;
      Set authenticating
  &lt;/button&gt;
  @code
  {
      private void UpdateAuthentication(bool? isAuthenticated)
      {
          if (!isAuthenticated.HasValue)
          {
              MyAuthenticationStateProvider.IsAuthenticating = true;
          }
          else
          {
              MyAuthenticationStateProvider.IsAuthenticating = false;
              MyAuthenticationStateProvider.IsAuthenticated = isAuthenticated.Value;
          }
  
          MyAuthStateProvider.NotifyAuthenticationStateChanged();
      }
  </code></pre>
  
  <p>And in my index.razor:</p>
  
  <pre><code>@page "/"
  @using System.Security.Claims
  @using Microsoft.AspNetCore.Components.Authorization
  @inject MyAuthenticationStateProvider MyAuthStateProvider
  
  &lt;h3&gt;ClaimsPrincipal Data&lt;/h3&gt;
  
  &lt;a href="/Login"&gt;Login&lt;/a&gt;
  
  &lt;button @onclick="GetClaimsPrincipalData"&gt;Get ClaimsPrincipal Data&lt;/button&gt;
  
  &lt;p&gt;@_authMessage&lt;/p&gt;
  
  @if (_claims.Count() &gt; 0)
  {
      &lt;ul&gt;
          @foreach (var claim in _claims)
          {
              &lt;li&gt;@claim.Type &amp;ndash; @claim.Value&lt;/li&gt;
          }
      &lt;/ul&gt;
  }
  
  &lt;p&gt;@_surnameMessage&lt;/p&gt;
  
  @code {
      private string _authMessage;
      private string _surnameMessage;
      private IEnumerable&lt;Claim&gt; _claims = Enumerable.Empty&lt;Claim&gt;();
  
  
      private async Task GetClaimsPrincipalData()
      {
          var authState = await MyAuthStateProvider.GetAuthenticationStateAsync();
          var user = authState.User;
  
          if (user.Identity.IsAuthenticated)
          {
              _authMessage = $"{user.Identity.Name} is authenticated.";
              _claims = user.Claims;
              _surnameMessage =
                  $"Surname: {user.FindFirst(c =&gt; c.Type == ClaimTypes.Surname)?.Value}";
          }
          else
          {
              _authMessage = "The user is NOT authenticated.";
          }
      }
  </code></pre>
  
  <p>And then my app.razor:</p>
  
  <pre><code>&lt;Router AppAssembly="@typeof(Program).Assembly"&gt;
      &lt;Found Context="routeData"&gt;
          &lt;AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /&gt;
      &lt;/Found&gt;
      &lt;NotFound&gt;
          &lt;CascadingAuthenticationState&gt;
              &lt;LayoutView Layout="@typeof(MainLayout)"&gt;
                  &lt;p&gt;Sorry, there's nothing at this address.&lt;/p&gt;
              &lt;/LayoutView&gt;
          &lt;/CascadingAuthenticationState&gt;
      &lt;/NotFound&gt;
  &lt;/Router&gt;
  </code></pre>
  
  <p>My startup.cs:</p>
  
  <p><code>
     public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }</p>
  
  <pre><code>    public IConfiguration Configuration { get; }
  
      // This method gets called by the runtime. Use this method to add services to the container.
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddAuthenticationCore();
          services.AddScoped&lt;MyAuthenticationStateProvider&gt;();
          services.AddScoped&lt;AuthenticationStateProvider&gt;(provider =&gt; provider.GetRequiredService&lt;MyAuthenticationStateProvider&gt;());
          services.AddRazorPages();
          services.AddServerSideBlazor();
          services.AddSingleton&lt;WeatherForecastService&gt;();            
  
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Error");
              // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
              app.UseHsts();
          }                        
  
  
          app.UseHttpsRedirection();
          app.UseStaticFiles();            
  
          app.UseRouting();
  
          app.UseAuthentication();
          app.UseAuthorization();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapBlazorHub();
              endpoints.MapFallbackToPage("/_Host");
          });
      }
  }
  </code></pre>
  
  <p></code></p>
  
  <p>The problem is the authorize component is not working, when I go to the login page and after I authorize, I get the Unauthorize message when I click on the counter component !  </p>
  
  <pre><code>@page "/counter"
  @attribute [Authorize]
  &lt;h1&gt;Counter&lt;/h1&gt;
  
  &lt;p&gt;Current count: @currentCount&lt;/p&gt;
  
  &lt;button class="btn btn-primary" @onclick="IncrementCount"&gt;Click me&lt;/button&gt;
  
  @code {
      private int currentCount = 0;
  
      private void IncrementCount()
      {
          currentCount++;
      }
  }
  </code></pre>
  
  <p>Any help would really be appreciated, I have tried to solve this problem yesterday until 3 am without success!</p>
  
  <p>Many thanks,</p>
  
  <p>Raphaël</p>