我需要永久阻止一个用户。我不明白为什么这个代码不工作。
这行UserManager.IsLockedOut(user.Id);
总是返回false
而不是true
。
也许有必要把这行UserManager.UserLockoutEnabledByDefault = true;
放在用户注册阶段?
using (var _db = new ApplicationDbContext())
{
UserStore<DALApplicationUser> UserStore = new UserStore<DALApplicationUser>(_db);
UserManager<DALApplicationUser> UserManager = new UserManager<DALApplicationUser>(UserStore);
UserManager.UserLockoutEnabledByDefault = true;
DALApplicationUser user = _userService.GetUserByProfileId(id);
bool a = UserManager.IsLockedOut(user.Id);
UserManager.SetLockoutEnabled(user.Id, true);
a = UserManager.IsLockedOut(user.Id);
_db.SaveChanges();
}
UserManager.SetLockoutEnabled(user.Id, true);
未锁定或解锁帐户。此方法用于永久启用或禁用给定用户帐户的锁定进程。就目前情况而言,您正在进行的调用基本上是将该用户帐户设置为受帐户锁定规则的约束。使用第二个参数false
进行调用,例如:
UserManager.SetLockoutEnabled(user.Id, false);
将允许您设置一个不受锁定规则约束的用户帐户-这对于管理员帐户可能很有用。
以下是UserManager.IsLockedOutAsync
的代码:
/// <summary>
/// Returns true if the user is locked out
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public virtual async Task<bool> IsLockedOutAsync(TKey userId)
{
ThrowIfDisposed();
var store = GetUserLockoutStore();
var user = await FindByIdAsync(userId).WithCurrentCulture();
if (user == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound,
userId));
}
if (!await store.GetLockoutEnabledAsync(user).WithCurrentCulture())
{
return false;
}
var lockoutTime = await store.GetLockoutEndDateAsync(user).WithCurrentCulture();
return lockoutTime >= DateTimeOffset.UtcNow;
}
可以看到,对于一个被分类为锁定的用户,必须像上面那样启用锁定,并且该用户的LockoutEndDateUtc
值必须大于或等于当前日期。
因此,要"永久"锁定帐户,可以执行以下操作:
using (var _db = new ApplicationDbContext())
{
UserStore<DALApplicationUser> UserStore = new UserStore<DALApplicationUser>(_db);
UserManager<DALApplicationUser> UserManager = new UserManager<DALApplicationUser>(UserStore);
UserManager.UserLockoutEnabledByDefault = true;
DALApplicationUser user = _userService.GetUserByProfileId(id);
bool a = UserManager.IsLockedOut(user.Id);
//user.LockoutEndDateUtc = DateTime.MaxValue; //.NET 4.5+
user.LockoutEndDateUtc = new DateTime(9999, 12, 30);
_db.SaveChanges();
a = UserManager.IsLockedOut(user.Id);
}
功能SetLockoutEnabled
不会锁定用户,它为用户启用锁定功能
UserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromHours(1); // lockout for 1 hour
UserManager.MaxFailedAccessAttemptsBeforeLockout = 5; // max fail attemps
await UserManager.AccessFailedAsync(user.Id); // Register failed access
它将记录一个失败,并锁定用户,如果锁定是启用的和失败计数达到。
在Login操作中将shouldLockout的值设置为true(默认为false)
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(vm.Email, vm.Password, vm.RememberMe, shouldLockout: true);