Click here to Skip to main content
13,660,780 members
Click here to Skip to main content
Add your own
alternative version

Stats

27.6K views
8 bookmarked
Posted 25 Nov 2017
Licenced CPOL

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

, 5 Dec 2017
Rate this:
Please Sign up or sign in to vote.
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.

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.

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

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

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)

Share

About the Author

Raihan Alam
Software Developer (Senior)
Australia Australia
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionwithout Database Pin
Oliver Larsen12-Apr-18 0:14
memberOliver Larsen12-Apr-18 0:14 
SuggestionNice article Pin
Tony Dong26-Jan-18 14:23
memberTony 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 5 Dec 2017
Article Copyright 2017 by Raihan Alam
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid