ASP.NET Core 实现用户认证,最常用、最推荐的方式就是使用 ASP.NET Core Identity——它是一套开箱即用、可扩展的身份验证与用户管理框架,支持注册、登录、密码重置、双因素认证、角色管理等核心功能。
一、创建项目时启用 Identity
新建 ASP.NET Core Web App(MVC 或 Razor Pages)时,在“身份验证类型”中选择“个人账户”(Individual Accounts),Visual Studio 或 CLI 会自动配置 Identity(含 Entity Framework Core 和 SQLite/SQL Server 数据库支持)。
若已存在项目,可通过以下方式手动添加:
安装 NuGet 包:Microsoft.AspNetCore.Identity.EntityFrameworkCore和
Microsoft.EntityFrameworkCore.SqlServer(或对应数据库提供程序) 在
Program.cs中调用
AddIdentityCore<applicationuser>()</applicationuser>或更常用的
AddDefaultIdentity<applicationuser>()</applicationuser>,并配置 Entity Framework 存储 添加迁移并更新数据库:
dotnet ef migrations add InitIdentity→
dotnet ef database update
二、理解 Identity 的核心组件
Identity 不是黑盒,关键类需了解:
ApplicationUser:继承自IdentityUser,可扩展邮箱、昵称、头像等字段 ApplicationDbContext:继承
IdentityDbContext<applicationuser></applicationuser>,负责用户、角色、登录、令牌等数据表映射 UserManager
[Authorize(Roles = "Admin")]使用
三、快速实现注册与登录
Identity 默认提供
/Identity/Account/Register和
/Identity/Account/Login页面(Razor Pages)。你只需: 确保
Program.cs中已注册 Identity 服务和端点:
app.MapRazorPages()和
app.UseAuthentication()、
app.UseAuthorization()顺序正确 在视图中用
@using Microsoft.AspNetCore.Identity和
@inject SignInManager<applicationuser> SignInManager</applicationuser>判断登录状态 保护控制器或页面:加
[Authorize]特性;仅允许未登录用户访问登录页:加
[AllowAnonymous]
例如,在
HomeController中限制访问:
[Authorize]
public IActionResult Dashboard() => View();
四、自定义与常见调整
Identity 灵活,但新手容易卡在细节:
改用邮箱登录:在ApplicationUser中保留
UserName设为邮箱值(无需改主键,Identity 默认用
UserName做用户名标识) 禁用用户名必填:重写
IdentityOptions,设
options.User.RequireUniqueEmail = true,并移除对
UserName的强依赖(需自定义 UserManager 行为) 密码策略简化:在
Program.cs配置
IdentityOptions.Password,比如关闭大小写/数字要求 使用 JWT 替代 Cookie 认证:不走 Identity UI,而是用
AddJwtBearer+ 自定义 Token 发放逻辑(适合 API 场景)
基本上就这些。Identity 入门不难,关键是先跑通默认流程,再按需定制。别一开始就试图替换所有默认实现——多数业务需求,靠配置和少量扩展就能满足。
