ASP.NET Core怎么实现用户认证 ASP.NET Core Identity入门方法

来源:这里教程网 时间:2026-02-21 17:38:56 作者:

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:处理用户生命周期操作(创建、密码设置、验证、锁定等) SignInManager:处理登录、登出、外部登录、双因素流程 RoleManager:管理角色(如 Admin、Editor),配合
[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
中保留
Email
字段,并在注册/登录逻辑中将
UserName
设为邮箱值(无需改主键,Identity 默认用
UserName
做用户名标识)
禁用用户名必填:重写
IdentityOptions
,设
options.User.RequireUniqueEmail = true
,并移除对
UserName
的强依赖(需自定义 UserManager 行为)
密码策略简化:在
Program.cs
配置
IdentityOptions.Password
,比如关闭大小写/数字要求
使用 JWT 替代 Cookie 认证:不走 Identity UI,而是用
AddJwtBearer
+ 自定义 Token 发放逻辑(适合 API 场景)

基本上就这些。Identity 入门不难,关键是先跑通默认流程,再按需定制。别一开始就试图替换所有默认实现——多数业务需求,靠配置和少量扩展就能满足。

相关推荐