Customizing ASP.NET Core Identity Razor Pages via Scaffolding (in an MVC app)

If you are trying to add the built-in ASP.NET Core Identity Authentication scaffolding to an MVC application, you will notice that traversing between MVC controller actions and simple requests to Razor Pages doesn't work as transparently as you might expect.

To scaffold the Identity Razor Pages so that we can customize them, we first do the following:

Right-click the project and select, "Add >> New Scaffolded Item..."


Select the Identity scaffolding template


From the next screen, select the Razor pages that you would like to scaffold for overriding/customizing


Once you have the scaffolded pages you will need to run this from the Developer console to generate the necessary ASP.NET Core Identity database tables: dotnet ef database update

If you want to be able to get to the Login page from an MVC controller, you will; need to an [AllowAnonymous] attribute to the Login.cshtml Razor Page code-behind class, and you will need to call the Login page while referencing the Area path in which it is located within the project file structure.

The folder structure for an MVC project overriding the built-in Identity auth Razor pages via scaffolding


An MVC logout link that you want to redirect to an overridden Identity auth Login Razor page might look like this in your _Layout view: 

The view link in the MVC's _Layout.cshtml

The controller redirect (note: new { area = "Identity" }); "/Pages/" is ignored for some reason..

In order to reach the Login Razor page (when not being authenticated) you will need to add the [AllowAnonymous] attribute to the LoginModel class a la:

With [AllowAnonymous] users will be able to reach the overridden Identity Login page from any controller action in your MVC application


An that's it. You can customize all of the front-end and back-end code of the scaffolded Identity Razor pages. This is an example of customization that uses the extRS service to create SSRS user accounts when a user registers a new Identity account for the app:

Scaffolding the Identity Razor pages allows you focus only on the authentication design and logic that you need to customize 


I'm not sure why but much of this is not documented (and what is documented is not easily found).

Lastly, do keep in mind that in order to override certain items like "_LoginPartial", you need to rename to view, as was done with "_LoginPartial2.cshtml" in the extRS project, for example.


References: 

https://github.com/sonrai-LLC/extRS/tree/main/ExtRS.Portal

https://extrs.net




    

    

No comments: