Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Implementing login functionality in asp.net core

Suggested Videos
Part 67 - ASP.NET Core Identity UserManager and SignInManager | Text | Slides
Part 68 - ASP.NET core identity password complexity | Text | Slides
Part 69 - Show or hide login and logout links based on login status in asp.net core | Text | Slides

In this video we will discuss implementing login functionality in an asp.net core application using the asp.net core identity API.


To implement the login functionality in an asp.net core application, we need to implement the following
  • Login View Model
  • Login View
  • A pair of Login action methods in the AccountController

LoginViewModel

To login a user, we need their Email which is the username, password and whether if they want a persistent cookie or session cookie.

public class LoginViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me")]
    public bool RememberMe { get; set; }
}

Session Cookie vs Persistent Cookie

Upon a successful login, a cookie is issued and this cookie is sent with each request to the server. The server uses this cookie to know that the user is already authenticated and logged-in. This cookie can either be a session cookie or a persistent cookie.

A session cookie is created and stored within the session instance of the browser. A session cookie does not contain an expiration date and is permanently deleted when the browser window is closed.

A persistent cookie on the other hand is not deleted when the browser window is closed. It usually has an expiry date and deleted on the date of expiry.

Login View

@model LoginViewModel

@{
    ViewBag.Title = "User Login";
}

<h1>User Login</h1>

<div class="row">
    <div class="col-md-12">
        <form method="post">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div class="checkbox">
                    <label asp-for="RememberMe">
                        <input asp-for="RememberMe" />
                        @Html.DisplayNameFor(m => m.RememberMe)
                    </label>
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Login</button>
        </form>
    </div>
</div>

Login Action in AccountController

using EmployeeManagement.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace EmployeeManagement.Controllers
{

    public class AccountController : Controller
    {
        private readonly SignInManager<IdentityUser> signInManager;

        public AccountController(SignInManager<IdentityUser> signInManager)
        {
            this.signInManager = signInManager;
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();
            return RedirectToAction("index", "home");
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(
                    model.Email, model.Password, model.RememberMe, false);

                if (result.Succeeded)
                {
                    return RedirectToAction("index", "home");
                }

                ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
            }

            return View(model);
        }
    }
}

asp.net core tutorial for beginners

9 comments:

  1. How to use with Entity framework as i have crated a table inside my database now i want to add multiple user what should i do i'm working on Asp mvc5

    ReplyDelete
  2. hi i am trying to implement login function but whenever i try to login i get error "Invalid Login Attempt"

    ReplyDelete
    Replies
    1. If you are using Identity then email should be verified before login

      Delete
  3. Hello. If anyone is using f username != email. You must first call var
    _MyUser = await userManager.FindByEmailAsync(model.Email);

    and then call
    var result = await signInManager.PasswordSignInAsync(_MyUser .UserName, model.Password, model.RememberMe, false);

    Another option would be calling SignInManager.UserManager.CheckPassword(_MyUser, model.Password);

    ReplyDelete
  4. Cookie not being sent. dont know why. implemented as an api. any fixes?

    ReplyDelete
  5. you did not add login in _Layout

    ReplyDelete
  6. Hi, I am getting this error:

    InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Haircut_Booking_Web_Application.Controllers.AccountLoginController'.

    Can you help please?

    ReplyDelete
  7. Severity Code Description Project File Line Suppression State
    Error CS0411 The type arguments for method 'IModelExpressionProvider.CreateModelExpression(ViewDataDictionary, Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly

    how to fix this ?

    ReplyDelete
  8. How can we check to user is already signed-in in another page?

    ReplyDelete

It would be great if you can help share these free resources