newcoder
newcoder

Reputation: 378

Disable prebuilt Razor UI pages after scaffolding identity

In VS2022, I started a new Razor page project with "Individual Accounts" selected as authenization type. I found that there are no identity-related code available for customization because they are prebuilt using the Razor UI. I want to customize the pages and so I generated the pages by the method suggested as below.

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-6.0&tabs=visual-studio&viewFallbackFrom=aspnetcore-2.1

After that, I wanted to disable the registration page after creating my admin account. I selected "Exclude from project" to Register.chtml as shown below.

enter image description here

Surprisingly, I found that the prebuilt Razor UI pages are automatically used when the generated pages are excluded(I can still access and use the url /Identity/Account/Register). How can I disable the prebuilt Razor UI pages?

Upvotes: 3

Views: 1279

Answers (2)

Rena
Rena

Reputation: 36705

You can add app.Map middleware like below:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.Map("/Identity/Account/Register", HandleRequest);
    app.Map("/Identity/Account/Login", HandleRequest);

    static void HandleRequest(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            await context.Response.WriteAsync("404 Not Found");
        });
    }

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

Upvotes: 5

Mike Brind
Mike Brind

Reputation: 30075

When you include the UI package, you opt in to using all of it. You can selectively disable pages by scaffolding them and then returning a NotFoundResult from both the OnGet and OnPost methods, but that can be laborious. You can also use Authorization to prevent access to pages or folders by specifying an authorization policy that is never applied to users, or a non-existent role, for example:

[Authorize(Roles ="Does Not Exist")]
public class RegisterModel : PageModel
{
   ...

Or, if you no longer need the Identity UI at all, uninstall the package from your application.

Upvotes: 2

Related Questions