DreamingOfSleep
DreamingOfSleep

Reputation: 1448

ASP.NET Core [Authorize] attribute allowing non-authed users to load a page

I have an ASP.NET Core Blazor app that uses Identity. This is set up in Program.cs as follows...

builder.Services.AddIdentity<User, IdentityRole>(options => {
    options.SignIn.RequireConfirmedAccount = true;
    // Password options skipped for brevity
    options.User.RequireUniqueEmail = true;
    options.SignIn.RequireConfirmedAccount = true;
  })
  .AddDefaultTokenProviders()
  .AddEntityFrameworkStores<AppDbContext>();

//... further down...

app.UseAuthentication();
app.UseAuthorization();

There is also code to add some users which I don't think is relevant, as they are added fine.

I can log in and out as expected, and if I use code like this on a Blazor page...

  [Inject]
  public AuthenticationStateProvider AuthenticationStateProvider { get; set; } = null!;

  private ClaimsPrincipal _me = null!;

  protected override async Task OnInitializedAsync() =>
    _me = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;

...then I can check if the current user is logged in by checking _me?.Identity?.IsAuthenticated.

This correctly identifies if the user is authed or not.

Now I want to secure a page, so only a logged-in user can see it. I added an attribute at the top of the code file...

[Authorize]
public partial class UserList {
  // rest of the class omitted for clarity

However, I can still access this page, even when not logged in. If I add the code to create _me as above, then it shows me that I'm not logged in, but still allows access to the page. I tried adding the attribute to the .razor file as follows...

@page "/users"
@attribute [Authorize]

...but it didn't make any difference.

Anyone able to see what I've done wrong? Not sure if I've posted all the code you need, so if I missed anything, please let me know.

Upvotes: 0

Views: 136

Answers (1)

Xinran Shen
Xinran Shen

Reputation: 9943

In App.razor file, use AuthorizeRouteView component instead of RouteView component.

<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />

More information please refer to link.

Upvotes: 1

Related Questions