In order to lockout a user account in ASP.NET Identity, we use two user properties: the LockoutEnabled property and the LockoutEndDateUtc property.
The LockoutEnabled property indicates that the lockout is enabled for a user. By setting this property to
it does not mean that the user is locked out, it only means that the user could be locked out.
The LockoutEndDateUtc property indicates when the lockout ends and be careful, any time in the past is considered not locked out.
Locking out a user
By using these two properties together, you can lockout a user for a specific amount of time.
// Locking out a user for 10 minutes user.LockoutEnabled = true; user.LockoutEndDateUtc = DateTimeOffset.Now.AddMinutes(10);
In preceding code, we enable the lockout for the user by setting the LockoutEnabled property to
After that, we add 10 minutes to the current datetime by using the AddMinutes method and we set the result value to the
LockoutEndDateUtc property. This will result in locking the user out for 10 minutes.
We can also use the methods SetLockoutEnabled and SetLockoutEndDate to modify the values
of these properties by passing the id of the user to lockout as a parameter. These methods are called by the UserManager
and they return an
// Locking out a user for 10 minutes var result = UserManager.SetLockoutEnabled(userId, true); var result = UserManager.SetLockoutEndDate(userId, DateTimeOffset.Now.AddMinutes(10));
In order to lockout a user definitely or at least until unlocking it again, set the LockoutEndDateUtc property
user.LockoutEnabled = true; user.LockoutEndDateUtc = DateTimeOffset.MaxValue; // OR var result = UserManager.SetLockoutEnabled(userId, true); var result = UserManager.SetLockoutEndDate(userId, DateTimeOffset.MaxValue);
Unlocking a user
In order to unlock a locked out user, you have to set the value of the LockoutEnabled property to
user.LockoutEnabled = false; // OR var result = UserManager.SetLockoutEnabled(userId, false);
In order to get the UserManager, and use the SetLockoutEnabled and the SetLockoutEndDate methods, you have to include the following namespaces :
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin;