Saturday, 3 October 2020

ASP.NET Core Identity: User Registration, Login and Logout functionality using ASP.NET Core MVC

 The complete code for this article is available in the Demo 2 folder in this repo https://github.com/ra1han/aspnet-core-identity.

Preparing Service and Middleware

We have to add MVC to the ConfigureServices method so that it can be used in the application.

We already know that the Configure method in the Startup class is used to configure the application's middleware. Currently, it has the following code which directly writes a "Hello World" response. We shall remove it and add MVC which will process the request.

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

The final code for these two methods will look like this:

public void ConfigureServices(IServiceCollection services)
{
	services.AddDbContext<applicationdbcontext>(options =>
					options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

	services.AddIdentity<applicationuser, identityrole="">()
														.AddEntityFrameworkStores<applicationdbcontext>()
														.AddDefaultTokenProviders();
	services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseAuthentication();

	app.UseMvc(routes =>
	{
		routes.MapRoute(
			name: "default",
			template: "{controller=Home}/{action=Index}/{id?}");
	});
}

Preparing ViewModels

In this, we will create two viewmodels for using in Registration and Login page.

  • LoginViewModel
  • RegisterViewModel

Preparing Controllers

We will create two controllers:

  • AccountController
  • HomeController

The Home controller looks like this:

[Authorize]
public class HomeController : Controller
{
	public IActionResult Index()
	{
		return View();
	}
}

The important point here is the [Authorize] attribute that we are using with the controller. This implies that if the user is not authenticated, he can't access this endpoint.

The Account controller looks like this (for brevity, I am only showing the public method signatures):

[Authorize]
public class AccountController : Controller
{
	public AccountController(UserManager<applicationuser> userManager, 
                             SignInManager<applicationuser> signInManager)
	{
		_userManager = userManager;
		_signInManager = signInManager;
	}

	[HttpGet]
	[AllowAnonymous]
	public async Task<iactionresult> Login(string returnUrl = null)
	{
	}

	[HttpPost]
	[AllowAnonymous]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Login(LoginViewModel model, string returnUrl = null)
	{
	}

	[HttpPost]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Logout()
	{
	}

	[HttpGet]
	[AllowAnonymous]
	public IActionResult Register(string returnUrl = null)
	{
	}

	[HttpPost]
	[AllowAnonymous]
	[ValidateAntiForgeryToken]
	public async Task<iactionresult> Register(RegisterViewModel model, string returnUrl = null)
	{
	}
}

We can see that all methods related to Registration or Login have [AlllowAnonymous] attribute so that only logged in users can access them.

For registration and authentication, we are using UserManager and SignInManager. They both are part of ASP.NET Core Identity and come through dependency injection.

Preparing Views

The Views are created in the Views folder. I am not explaining much about them as they are pretty standard MVC Views.

Using the Application

If we run the application, it will go to the Login page as no user is logged in.

Image 1

If we go to the Register page, it will look like this:

Image 2

After registering and logging in, the page will look like this:

Image 3

This is cookie based authentication and in the next article, we shall see how to implement token based authentication in ASP.NET Core Identity.

No comments:

Post a Comment