You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6 Identity如何禁用自定义用户表中锁定用户登录

实现自定义Lockout字段控制用户登录锁定

不需要自定义SignInManager,通过扩展自定义UserStore实现IUserLockoutStore<TUser>接口,就能让默认的PasswordSignInAsync返回IsLockedOut状态,适配你的自定义Lockout字段逻辑。

具体步骤

1. 实现IUserLockoutStore接口

在你的自定义UserStore中实现IUserLockoutStore<AppUser>接口,将数据库的Lockout字段映射到Identity的锁定检查逻辑:

public class CustomUserStore : IUserStore<AppUser>, IUserLockoutStore<AppUser>
{
    // 保留你已实现的IUserStore相关方法

    public Task<DateTimeOffset?> GetLockoutEndDateAsync(AppUser user, CancellationToken cancellationToken)
    {
        // 若Lockout为true,返回远未来时间表示用户持续锁定;否则返回null
        return Task.FromResult(user.Lockout ? (DateTimeOffset?)DateTimeOffset.MaxValue : null);
    }

    public Task SetLockoutEndDateAsync(AppUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken)
    {
        // 因锁定由自定义字段控制,此处可留空实现
        return Task.CompletedTask;
    }

    public Task<bool> GetLockoutEnabledAsync(AppUser user, CancellationToken cancellationToken)
    {
        // 直接返回自定义Lockout字段的值
        return Task.FromResult(user.Lockout);
    }

    public Task SetLockoutEnabledAsync(AppUser user, bool enabled, CancellationToken cancellationToken)
    {
        // 可选:允许通过Identity API更新Lockout字段
        user.Lockout = enabled;
        return Task.CompletedTask;
    }

    public Task<int> IncrementAccessFailedCountAsync(AppUser user, CancellationToken cancellationToken)
    {
        // 需求与登录失败次数无关,返回0
        return Task.FromResult(0);
    }

    public Task ResetAccessFailedCountAsync(AppUser user, CancellationToken cancellationToken)
    {
        // 空实现即可
        return Task.CompletedTask;
    }

    public Task<int> GetAccessFailedCountAsync(AppUser user, CancellationToken cancellationToken)
    {
        // 返回0,忽略失败次数逻辑
        return Task.FromResult(0);
    }
}

2. 注册自定义UserStore

在Program.cs(或Startup.cs)中确保UserStore被正确注册到Identity服务:

builder.Services.AddScoped<IUserStore<AppUser>, CustomUserStore>();
builder.Services.AddIdentity<AppUser, IdentityRole>()
    .AddUserStore<CustomUserStore>()
    .AddDefaultTokenProviders();

3. 无需修改现有Login逻辑

完成上述配置后,当用户的Lockout字段为true时,PasswordSignInAsync会自动返回SignInResult.LockedOut,你的现有Login动作中else if (result.IsLockedOut)分支会触发,返回对应的锁定提示。


内容的提问来源于stack exchange,提问作者jstuardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:10:18