Search code examples
asp.net-coreasp.net-identity

Where are the authorize attributes coming from on the identity pages?


A scaffolded ASP.NET Core Identity UI comes without authorization attributes. For example, LogOut.cshtml and LogOut.cshtml.cs have no authorization attribute. Yet, an unauthenticated user is redirected to the login page if visiting it, and indeed investigating the endpoint data for Identity/Account/LogOut indicates the presence of an AuthorizeAttribute (I used this neat way of displaying the endpoint data).

This is weird for a number of reasons. First, the LogOut.chtml contains logic for the unauthenticated case. On the sources, the original model in LogOut.chtml.cs even has an AllowAnonymous attribute.

Besides this particular weirdness with LogOut, I'm more genreally trying to understand what determines those attributes/configurations here if it's not the scaffolded pages I have in my code - and none of them came with any authorization attributes.

I have everything straight from the wizard, there's also nothing done to the AppBuilder except MapRazorPages that should do something identity-specific.


Solution

  • Identity.UI configures the global Authorize property for Logout and Manage by default, but not configured for other pages. So you need to add the AllowAnonymous attribute to directly access the Logout Page without logging in.

    You can see this in the source code of IdentityDefaultUIConfigureOptions. The AddDefaultIdentity you used when adding Identity contains DefaultUI, so it will add constraints to specific pages by default.

    Also, if you don't want to use the AllowAnonymous attribute, you can also use the global configuration in Program.cs:

    builder.Services.AddRazorPages(option =>
    {
        option.Conventions.AllowAnonymousToAreaPage("Identity", "/Account/Logout");
    });
    

    Reference link: Razor Pages authorization conventions in ASP.NET Core.

    Hope this can help you.