How to lock and unlock account in Asp.Net Identity provider

I have release Version 1.0.1 of Identity Management Dashboard. In this release I have added new feature of locking and unlocking user accounts for Asp.Net identity users.

NuGet Package

You can download the updated package from following location.

Asp.Net Identity Management Dashboard

Locking Apis

If you are looking into implementing locking and unlocking in your own application, then here are some details that will help you. Following methods in UserManager object play main role.

  • SetLockoutEnabledAsync
  • SetLockoutEndDateAsync
  • IsLockedOutAsync

IsLockedOutAsync

As the name suggests, this method allows you get Boolean value indicating if an account is locked or unlocked.

SetLockoutEnabledAsync

This method takes user id and Boolean flag indicating your locking intention as two parameters. It is very straight forward API and there is nothing fancy to it. You should always call ResetAccessFailedCountAsync method after you have unlocked an account. This will ensure that all

SetLockoutEndDateAsync

As the name suggests that you will use this method to set the date for when the lock out is going to expire. First I thought I could get away by nothing using this method and leave LockOutEndDateUtc field value to default value in database. The default value is NULL. It turned out that this date plays a very important role when you are using IsLockedOutAsync method to check lock out status. This method first checks if Boolean flag is set for lock out. Next it checks if LockoutEndDate is set to a value in future. If LockoutEndDate is not set, then return value from GetLockoutEndDateAsync is always set to DateTimeOffset.MinValue. What this means is that check in IsLockedOutAsync will always fail because it checks against DateTimeOffet.Now. So return value from IsLockedOutAsync is always false. So if you are looking into locking an account for indefinite period of time, then you can pass DateTimeOffset.MaxValue to SetLockoutEndDateAsync method.

Following code snippet shows how this has been implemented in this dashboard.

public virtual async Task<identityresult> LockUserAccount(string userId, int? forDays)
{
    var result = await this.SetLockoutEnabledAsync(userId, true);
    if (result.Succeeded)
    {
        if (forDays.HasValue)
        {
            result = await SetLockoutEndDateAsync(userId, DateTimeOffset.UtcNow.AddDays(forDays.Value));
        }
        else
        {
            result = await SetLockoutEndDateAsync(userId, DateTimeOffset.MaxValue);
        }
    }
    return result;
}
public virtual async Task<identityresult> UnlockUserAccount(string userId)
{
    var result = await this.SetLockoutEnabledAsync(userId, false);
    if (result.Succeeded)
    {
        await ResetAccessFailedCountAsync(userId);
    }
    return result;
}

Search

Social

Weather

21.3 °C / 70.4 °F

weather conditions Clouds

Monthly Posts

Blog Tags