ASP.NET Core Identity Pages with ASP.NET Core 2.1

Creating a ASP.NET Core 2.1 project with identity configured you might miss controllers and many views that all have been available with ASP.NET Core 2.0 projects. All this functionality has been put into a Razor Class Library – a new feature with ASP.NET Core 2.1. You don’t have to deal with this code in your application. Not having the code you might ask how to customize the views. There’s an easy way to do this as shown here.

Authentication via fingerprint

Identity with ASP.NET Core 2.0

Creating a new ASP.NET Core 2.0 project, using the project template with Visual Studio 2017, you can change the authentication to store accounts locally. With this option, many classes and views are created:

  • Controller – AccountController and ManageController
  • Data – ApplicationDbContext
  • Extensions – extension methods for emails and SMS
  • Models – several view-model types in AccountViewModels and ManageViewModels
  • Services – EmailSender
  • Views – used by the AccountController and the ManageController

Store user accounts in-app

This functionality allows registration of users, login with a password and 2FA (2 Factor Authentication), if users forgot the password login via recovery code, logout, changing the password…

In the ConfigureServices method of the Startup class, the database context for storing all user information is specified with the AddDbContext method specifying the ApplicationDbContext class. Invoking the AddIdentity extension method configures the ApplicationUser and IdentityRole for user and role information, and maps it to the EC Core context. The method AddDefaultTokenProviders configures the token providers for data protector, phone number, email, and authenticator. The registration of the service class EmailSender for the IEmailSender contract just contains an empty implementation – you need to create an implementation for the SendMailAsync method to have functionality to send emails. The Configure method registers middleware. With the method UseAuthentication, the AuthenticationMiddleware is used with every request.


public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

view raw

Startup.cs

hosted with ❤ by GitHub

Using Identity with ASP.NET Core 2.1

Creating the same with ASP.NET Core 2.1, the result is very different. The two controllers are missing, there are no views and no view-models. Just the EF Core context ApplicationDbContext to map user and roles to the database are still here.

You can find the new folder Areas/Identity/Pages with the file _ViewStart.cshtml. This is a configuration for the identity pages coming from the library: the layout file part of the application is used by all the Razor pages in the Identity area. This is a simple way to customize the look of the views, it will use the same layout as used by the application.


@{
Layout = "/Views/Shared/_Layout.cshtml";
}

The startup code has been simplified – and extended. For being GDPR conform, ASP.NET Core 2.1 adds support for cookie consent.


public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

view raw

Startup.cs

hosted with ❤ by GitHub

Where is the code? Customizing the UI

Where is the code for the controllers and the views? The implementation has been changed from the MVC architecture to Razor Pages. The Razor Pages are implemented in a library. The source code is available in the GitHub identity repository. The new NuGet package referenced is Microsoft.AspnetCore.Identity.UI.

Razor Pages allow code for views to be either in the file for the view itself, or a code-behind page.

In case you need more customization of the pages, you can access the source code at GitHub to create your own pages, or see what CSS classes are used for easy customization. There’s also an easy way from Visual Studio to customize the pages. All you need to do is open the context menu while selecting the application in the Solution Explorer, and selecting the menu Add | New Scaffold Item…. From there, select Identity to override the Identity pages.

Add Scaffold for Identity

The new dialog opened allows to override all the pages, or select the pages that you need to change.

Override Identity Pages

With the sample code, Login and Register has been selected. You can find the generated pages within the Identity area. You can now completely customize the user interfaces along with the code-behind for the implementation.

Summary

Using ASP.NET Core 2.1, your code has been simplified by removing all the views and the controllers for authentication. Default functionality is coming from a library – a library making use of Razor Pages. In case you need customization other than having different styles for the HTML controls, you can easily create the pages with code-behind functionality by using Visual Studio 2017 and Scaffolding.

Read more about Razor Pages in the book Professional C# 7 and .NET Core 2.0.

Get the complete sample with ASP.NET Core 2.0 and 2.1 authentication from More Samples!

Enjoy programming and learning,
Christian

If you found this information valuable and want to return me a favor, then buy me a coffee.

Buy Me A Coffee

8 thoughts on “ASP.NET Core Identity Pages with ASP.NET Core 2.1

  1. Coming from .NET Framework MVC, to using .NET Core 2.1 Pages for the first time. It was not obvious at all how to customize the account related views. It really had me stumped. Thanks for the explanation and pointing out Add -> New Scaffold Item.

    Like

  2. Nice post! Really a nice list is presented by you. In my opinion, this list helps the programmer to understand the .NET programming. I hope to you to present this type of post in the future also.
    Thanks for sharing the information.

    Like

  3. I’m left completely confused by this.

    I’m know my asp.net core 2.1 web app adds MVC services in Startup.cs but I don’t want to use cshtml or get into the whole mvc thing as I’m using an Angular 7 front end SPA to send http requests to my web app (API).

    MVC cshtml and razor syntax is horrible compared to Angular and c# !

    So, how do I use the authentication mentioned here:
    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio#scaffold-identity-into-an-empty-project

    without using the razor class library ?

    Like

    1. Not having ever looked at it, my guess is the controller methods are probably implemented to return Json results. You could call those directly. If there was redirect logic, you could either handle that client side or you could write your own controller methods that do not include those.

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.