ASP.NET Identity
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 .NET 8 中的 ASP.NET Identity。Identity 是一个会员系统,用于向 ASP.NET 应用程序添加登录功能。
ASP.NET Identity 提供了一个强大的框架来管理用户、密码、配置文件数据、角色、声明、令牌等。它支持外部登录和双因素身份验证。
基本定义
ASP.NET Identity 是 ASP.NET 应用程序的现代身份验证系统。它用更灵活的架构取代了旧的 ASP.NET Membership 系统。
Identity 支持各种存储提供程序,包括 SQL Server、Azure 表存储和 NoSQL 数据库。它设计用于与 OWIN 中间件配合使用。
主要功能包括用户管理、基于角色的授权、基于声明的身份验证和外部提供程序集成。它高度可定制。
ASP.NET Identity 示例
以下示例演示了在 .NET 8 应用程序中设置 ASP.NET Identity,包括用户注册和登录。
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这为 ASP.NET Identity 设置了基本配置。AddIdentity 方法使用默认的用户和角色类型配置身份服务。
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model if needed
}
}
IdentityDbContext 提供了 Identity 所需的所有数据库表。它继承自具有 Identity 特定配置的 DbContext。
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(
model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
}
此控制器演示了用户注册、登录和注销功能。UserManager 负责创建用户,而 SignInManager 负责管理身份验证。
Register 操作使用电子邮件和密码创建新用户。Login 操作使用凭据对用户进行身份验证。这两个操作都遵循标准的 Identity 模式。
错误处理已内置到 Identity 系统中。用户创建或身份验证期间的错误会添加到 ModelState 中,以便在视图中显示。
来源
Microsoft ASP.NET Core Identity 文档
在本文中,我们探讨了 .NET 8 中的 ASP.NET Identity。这个强大的框架提供了全面的身份验证和授权功能。