Disable User in ASPNET identity 2.0

When you create a site with the Identity bits installed, your site will have a file called “IdentityModels.cs”. In this file is a class called ApplicationUser which inherits from IdentityUser.

// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://devblogs.microsoft.com/aspnet/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates/ to learn more.
public class ApplicationUser : IdentityUser

There is a nice link in the comments there, for ease click here

This tutorial tells you exactly what you need to do to add custom properties for your user.

And actually, don’t even bother looking at the tutorial.

  1. add a property to the ApplicationUser class, eg:

    public bool? IsEnabled { get; set; }

  2. add a column with the same name on the AspNetUsers table in your DB.

  3. boom, that’s it!

Now in your AccountController, you have a Register action as follows:

public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email, IsEnabled = true };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)

I’ve added the IsEnabled = true on the creation of the ApplicationUser object. The value will now be persisted in your new column in the AspNetUsers table.

You would then need to deal with checking for this value as part of the sign in process, by overriding PasswordSignInAsync in ApplicationSignInManager.

I did it as follows:

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool rememberMe, bool shouldLockout)
    {
        var user = UserManager.FindByEmailAsync(userName).Result;

        if ((user.IsEnabled.HasValue && !user.IsEnabled.Value) || !user.IsEnabled.HasValue)
        {
            return Task.FromResult<SignInStatus>(SignInStatus.LockedOut);
        }

        return base.PasswordSignInAsync(userName, password, rememberMe, shouldLockout);
    }

Your mileage may vary, and you may not want to return that SignInStatus, but you get the idea.

Leave a Comment