ASP.NET Core怎么实现用户认证 Identity框架入门教程

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

ASP.NET Core 中实现用户认证,最常用、最推荐的方式就是使用内置的 Identity 框架。它不是第三方库,而是微软官方提供的、开箱即用的用户管理解决方案,支持注册、登录、角色、密码重置、双因素认证等核心功能。

一、创建项目时启用 Identity

新建 ASP.NET Core Web App(MVC 或 Razor Pages)时,在“身份验证类型”中选择“个人账户”(Individual User Accounts),Visual Studio 会自动为你配置好 Identity(基于 EF Core + SQLite/SQL Server)。

如果你用 CLI 创建项目,可加参数:

dotnet new mvc -au Individual

这样生成的项目已包含:
• 用户注册/登录/登出页面(Account 控制器或 Pages/Account)

ApplicationDbContext
继承自
IdentityDbContext

ApplicationUser
类(可扩展的用户模型)
• 默认数据库迁移脚本

二、理解 Identity 的核心组件

Identity 不是黑盒,关键类有这几个:

ApplicationUser:继承
IdentityUser
,是你自己的用户实体(可加 Phone、Avatar 等字段)
ApplicationDbContext:继承
IdentityDbContext<applicationuser></applicationuser>
,负责与数据库交互
UserManager:处理用户生命周期操作(创建、密码重置、确认邮箱等) SignInManager:处理登录、登出、Cookie 发放、两步验证等 RoleManager:管理角色(如 Admin、Editor)

这些服务在

Program.cs
中通过
AddDefaultIdentity<applicationuser>()</applicationuser>
自动注册,无需手动 AddScoped。

三、快速添加登录/注册功能(无 UI 时)

如果项目没带 Account 页面(比如 API 项目或空模板),你可以手动添加:

Program.cs
中确保已调用:
builder.Services.AddDefaultIdentity<applicationuser>(options => options.SignIn.RequireConfirmedAccount = false).AddEntityFrameworkStores<applicationdbcontext>();</applicationdbcontext></applicationuser>
Configure
方法里启用认证中间件:
app.UseAuthentication();<br>app.UseAuthorization();
(顺序不能错)
控制器中注入
UserManager<applicationuser></applicationuser>
SignInManager<applicationuser></applicationuser>
即可调用
CreateAsync
CheckPasswordSignInAsync
等方法

例如登录逻辑片段:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);<br>if (result.Succeeded) { return RedirectToAction("Index", "Home"); }

四、常见定制需求怎么加

Identity 灵活,大部分定制只需改配置或继承:

改用户名字段为邮箱登录:在
Program.cs
配置
IdentityOptions

options.User.RequireUniqueEmail = true;<br>options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@.-_+";
密码策略收紧
options.Password.RequireDigit = true;<br>options.Password.RequiredLength = 8;
用手机号注册登录:继承
IdentityUser
PhoneNumber
字段,并在注册逻辑中设置
user.PhoneNumber = model.Phone
,再启用短信验证(需集成 SMS 服务)
角色授权控制访问:用
[Authorize(Roles = "Admin")]
或策略授权(Policy-based Authorization)

基本上就这些。Identity 入门不难,关键是理解 UserManager / SignInManager 的职责边界,别试图绕过它们自己写 Cookie 或查数据库——框架已经帮你兜底了。

相关推荐