Click here to Skip to main content
15,884,176 members
Articles / Web Development / ASP.NET / ASP.NET Core

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

Rate me:
Please Sign up or sign in to vote.
3.48/5 (10 votes)
5 Dec 2017CPOL2 min read 76.8K   10   2
Authentication using ASP.NET Core MVC and identity

Introduction

This is the second article of a series of articles on ASP.NET Core Identity.

In the previous article, we set up a project with identity database. In this article, we shall use that project to implement user authentication functionalities 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.

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

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

C#
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:

C#
[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):

C#
[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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionwithout Database Pin
Oliver Larsen12-Apr-18 0:14
Oliver Larsen12-Apr-18 0:14 
SuggestionNice article Pin
Tony Dong26-Jan-18 14:23
Tony Dong26-Jan-18 14:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.