Back to: ASP.NET MVC Tutorial For Beginners and Professionals
Login User in ASP.NET Identity
In this article, I am going to discuss Login a User in ASP.NET Identity. Please read our previous article where we discussed Username and Email Policy in ASP.NET Identity.
Login User Functionality in ASP.NET Identity
Now, we will start with how to implement the Authentication feature using ASP.NET Identity. So, the first step is to provide the login functionality. In order to log in user using ASP.NET Identity, we need to use the PasswordSignIn method of the ApplicationSignInManager class.
PasswordSignIn Method of ApplicationSignInManager Class:
The PasswordSignIn method of ApplicationSignInManager Class is used to sign in a user using its username and password and returns the result of the operation as a SignInStatus enumeration as follows.
SignInStatus result = SignInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
The PasswordSignIn method is called by the ApplicationSignInManager instance which is responsible for performing the sign-in operations in ASP.NET Identity.
We will discuss Remember Me and shouldLockout in detail in our upcoming articles. You can also use the Async version of the PasswordSignIn method as follows.
PasswordSignIn result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout: false);
What is SignInStatus?
If you go to the definition of SignInStatus, then you will see that it is an enumeration with the following signature.
The SignInStatus is an enumeration that represents the possible outcomes from a sign-in attempt. The following are the possible outcomes.
- Success: The user sign-in was successful
- LockedOut: The user is locked out
- RequiresVerification: The sign-in operation requires additional verification (used in two-factor authentication)
- Failure: The user sign-in failed
How to get an Instance of ApplicationSignInManager in ASP.NET Identity?
If you see, we are calling the PasswordSign or PasswordSignInAsync method using an instance of ApplicationSignInManager. The question is how we can get an instance of the ApplicationSignInManager. So, we need to use the Get method to get the ApplicationSignInManager instance from the OWIN context as follows.
ApplicationSignInManager SignInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
Note: Like the ApplicationUserManager, the ApplicationSignInManager is also defined in the IdentityConfig.cs file.
Namespace:
In order to use the Get method, the PasswordSignIn method, and the SignInStatus enum, you have to include the following namespace:
using Microsoft.AspNet.Identity.Owin;
Login HTTP Post Action Method:
If you open the Account Controller, then you will see the HTTP Post Login Action method already implemented. So, you can use that already implemented Login HTTP Post action method or you can comment on the existing one and create a new Login HTTP Post action method as follows. The [ValidateAntiForgeryToken] attribute is used to prevent the forgery of a request. The [AllowAnonymous] attribute allows to access this method without any authentication and authorization.
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginViewModel model) { if (!ModelState.IsValid) { return View(model); } //First get the user Details by Email ID, as the user name is required for login //Create an Instance of ApplicationUserManager ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); //Get the User Details by using FindByEmail Method var user = UserManager.FindByEmail(model.Email); //Create an Instance of ApplicationSignInManager ApplicationSignInManager SignInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); //Call the FindByEmail method using ApplicationSignInManager Instance SignInStatus result = SignInManager.PasswordSignIn(user.UserName, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToAction("Index", "Home"); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt.."); return View(model); } }
In the above code, we get the information of the user to authenticate via an HTTP Post request. We get the sign-in manager from the OWIN context by using the Get method and then we use the PasswordSignIn method in order to sign in this user. We redirect the user to the appropriate view based on the result of the sign-in operation. If the returned SignInStatus value is Failure, we add an error message to the ModelState by using the AddModelError method.
In this Login Action method, we are using the following LoginViewModel class. The LoginViewModel object is the ViewModel that we are using in order to render and validate the Login view.
public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } }
In the next article, I am going to discuss How to Implement Remember me Feature in ASP.NET Identity or How the Remember Me Feature is Implemented in ASP.NET Identity. Here, in this article, I try to explain Login a User in ASP.NET Identity. I hope you enjoy this Login a User in ASP.NET Identity article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.