.NET Core 8.0.1 AspNetCore.Identity如何禁用双因素认证
解决.NET Core 8 Identity禁用2FA并移除相关字段/端点的方法
1. 全局禁用2FA相关配置
.NET Core 8的Identity配置结构有所调整,原版本的options.TwoFactor属性已被拆分,你可以通过以下方式全局关闭2FA功能:
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options => { // 关闭手机号验证要求(2FA的核心依赖项之一) options.SignIn.RequireConfirmedPhoneNumber = false; // 禁用账号锁定的2FA关联逻辑 options.Lockout.AllowedForNewUsers = false; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
如果是纯API场景使用AddIdentityCore,配置逻辑一致:
builder.Services.AddIdentityCore<ApplicationUser>(options => { options.SignIn.RequireConfirmedPhoneNumber = false; }) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
2. 自定义登录模型,移除冗余字段
默认登录请求模型包含2FA相关字段,你可以自定义仅保留必要字段的模型,再实现自己的登录接口:
public class CustomLoginRequest { public string Email { get; set; } public string Password { get; set; } public bool RememberMe { get; set; } }
在自定义Auth控制器中实现登录逻辑:
[ApiController] [Route("api/auth")] public class AuthController : ControllerBase { private readonly SignInManager<ApplicationUser> _signInManager; public AuthController(SignInManager<ApplicationUser> signInManager) { _signInManager = signInManager; } [HttpPost("login")] public async Task<IActionResult> Login(CustomLoginRequest model) { if (!ModelState.IsValid) return BadRequest(ModelState); var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) return Ok(new { Token = "此处替换为你的JWT令牌生成逻辑" }); return Unauthorized("登录失败"); } }
3. 禁用Identity默认API端点
如果不需要Identity自带的端点,可直接关闭默认API注册:
builder.Services.AddIdentityCore<ApplicationUser>(options => { // 其他配置项 }) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddApiEndpoints(options => { // 禁用所有默认Identity端点 options.RegisterAllEndpoints(false); // 或按需禁用单个端点:options.RegisterEndpoint(IdentityEndpointNames.Login, false); });
同时在Program.cs中不要调用app.MapIdentityApi<ApplicationUser>(),这样默认的2FA相关端点就不会出现在Swagger中。
4. 清理用户实体冗余字段(可选)
如果你的ApplicationUser继承自IdentityUser,默认会包含TwoFactorEnabled等字段,若不需要可忽略(全局禁用后不会触发相关逻辑);若要彻底精简,可自定义用户实体仅保留必要字段:
public class ApplicationUser : IdentityUser { // 仅保留你需要的属性,如Email、UserName等 }
完成以上操作后,Swagger的登录请求将不再显示twoFactorCode和twoFactorRecoveryCode字段,2FA相关端点也会被移除。
内容的提问来源于stack exchange,提问作者Scott Jibben
相关产品推荐
相关产品推荐

