Disable registration template in ASP NET core

How can I disable the registration form in ASP NET Core 2.2.0+?

Just to get and remove the appropriate model, I can not, because it is not in the project, according to the documentation, I understand that this is connected with something like "ConfigureApplicationPartManager"

Link here

but I can not find an appropriate example to disable it

the goal is to disable the registration of new users, leaving only the Login \ Password form

services.AddMvc()
            .ConfigureApplicationPartManager(x =>
            {


                var thisAssembly = typeof(IdentityBuilderUIExtensions).Assembly;
                var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(thisAssembly, throwOnError: true);
                var relatedParts = relatedAssemblies.ToDictionary(
                    ra => ra,
                    CompiledRazorAssemblyApplicationPartFactory.GetDefaultApplicationParts);
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Upvotes: 21

Views: 14270

Answers (4)

Ogglas
Ogglas

Reputation: 70184

For ASP.NET Core 3.1 and up you can scaffold the page from Visual Studio GUI. Install NuGet Microsoft.VisualStudio.Web.CodeGeneration.Design and then do it like this:

  • From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • From the left pane of the Add New Scaffolded Item dialog, select Identity > Add.
  • In the Add Identity dialog, select the options you want.
    • Select your existing layout page, or your layout file will be overwritten with incorrect markup:
      • ~/Pages/Shared/_Layout.cshtml for Razor Pages
      • ~/Views/Shared/_Layout.cshtml for MVC projects
      • Blazor Server apps created from the Blazor Server template (blazorserver) aren't configured for Razor Pages or MVC by default. Leave the layout page entry blank.
    • Select the + button to create a new Data context class. Accept the default value or specify a class (for example, MyApplication.Data.ApplicationDbContext).
  • Select Add.

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-6.0&tabs=visual-studio#scaffold-identity-into-a-razor-project-with-authorization

You can then follow the guide from MS/@Niels R.:

https://stackoverflow.com/a/58852405/3850405

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

Upvotes: 2

Bouke Versteegh
Bouke Versteegh

Reputation: 4677

Another way to solve it is using Middleware, and blocking all routes with specific PageModels.

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

        var blockedPages = new [] {
            typeof(RegisterModel),
            typeof(RegisterConfirmationModel),
        };
        app.Use(async (context, next) =>
        {
            var pageActionDescriptor = context.GetEndpoint()?.Metadata.GetMetadata<PageActionDescriptor>();
            var page = (pageActionDescriptor as CompiledPageActionDescriptor)?.ModelTypeInfo.BaseType;

            if (blockedPages.Contains(page))
            {
                context.Response.Redirect("/");
                return;
            }
            await next.Invoke();
        });
    }
}

Upvotes: 2

Mardok
Mardok

Reputation: 674

Another option is just to remove Register link and redirect from register to login in your Startup class:

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/Identity/Account/Register", context => Task.Factory.StartNew(() => context.Response.Redirect("/Identity/Account/Login", true, true)));
            endpoints.MapPost("/Identity/Account/Register", context => Task.Factory.StartNew(() => context.Response.Redirect("/Identity/Account/Login", true, true)));
        });

Upvotes: 21

Niels R.
Niels R.

Reputation: 7364

You can specify which parts to scaffold. The following is an excerpt from the ASP.NET Core documentation. Link to the source below.

To disable user registration:

  • Scaffold Identity. Include Account.Register, Account.Login, and Account.RegisterConfirmation. For example:
dotnet aspnet-codegenerator identity -dc RPauth.Data.ApplicationDbContext --files "Account.Register;Account.Login;Account.RegisterConfirmation"
  • Update Areas/Identity/Pages/Account/Register.cshtml.cs so users can't register from this endpoint:
public class RegisterModel : PageModel
{
    public IActionResult OnGet()
    {
        return RedirectToPage("Login");
    }

    public IActionResult OnPost()
    {
        return RedirectToPage("Login");
    }
}
  • Update Areas/Identity/Pages/Account/Register.cshtml to be consistent with the preceding changes:
@page
@model RegisterModel
@{
    ViewData["Title"] = "Go to Login";
}

<h1>@ViewData["Title"]</h1>

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
  • Comment out or remove the registration link from Areas/Identity/Pages/Account/Login.cshtml
@*
<p>
    <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
*@
  • Update the Areas/Identity/Pages/Account/RegisterConfirmation page.
    • Remove the code and links from the cshtml file.
    • Remove the confirmation code from the PageModel:
[AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
    public IActionResult OnGet()
    {  
        return Page();
    }
}

Source: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio#disable-register-page

More information about dotnet aspnet-codegenerator: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/tools/dotnet-aspnet-codegenerator

Upvotes: 16

Related Questions