Disable A Specific User in ASP.NET Core Identity 2.0

I am writing this post simply to document a used case I had a few days ago. I basically wanted to disable a user instead of deleting the meta data from the system.
Since the project was built with regular ASP.Net Core Identity, It didn’t take too long for me to figure this out.

What’s ASP.Net Core Identity?

It is a simple membership system that add login capability to any asp.net Core applications. ASP.Net Core Identity supports external login providers such as Facebook, Twitter, Microsoft, and Google.
In case you would like to learn more about it, feel free to read this post on identity.

Implementation In ASP.NET Core Identity 2.0

I had to add a new property called “IsActive” as shown in the code snippet below to the “ApplicationUser.cs” class to disable the user in the system.

namespace UserApp.Models
{
 //Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsActive { get; set; }
    }
}

Next, I run migration to add the new column to the AspNetUsers table.

Now that I have the new column added to the table, I need to set the IsActive flag during registration.

Where do you update the IsActive flag by default?
Find the action method called RegisterAsync in the “AccountController.cs” and

 public async Task RegisterAsync(RegisterViewModel model, string returnUrl = null)
 {
   ViewData["ReturnUrl"] = returnUrl;
   if (ModelState.IsValid)
   {
        var user = new ApplicationUser
        {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    IsActive = true
         };
         var result = await _userManager.CreateAsync(user, model.Password);
         if (result.Succeeded)
         {
           _logger.LogInformation("User created a new account with password.");

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
            await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
            logger.LogInformation("User created a new account with password.");
            return RedirectToAction(nameof(ConfirmRegistration));
         }
         AddErrors(result);
     }

     // If we got this far, something failed, redisplay form
     return View(model);
 }

Finally, after running the application and register a brand new user I was able to verify the data in the database. In case you need already have some existing users, you’ll simply need to run an update query to set their flag to active. That’s it!!!

Leave a Reply

Your email address will not be published. Required fields are marked *