C# (.NET) 中的授权与身份验证
在现代 .NET 平台的 Web 开发中,身份验证(验证用户身份)和授权(验证访问权限)是基础性主题。ASP.NET Core 的库和内置机制为实现这些任务提供了强大而灵活的工具。在本文中,我们将详细分析主要方法,包括使用 JWT(JSON Web Tokens)、ASP.NET Core Identity 和内置的中间件组件。
基本概念
- 身份验证 (Authentication) — 验证用户身份的过程(例如,用户名 + 密码)。
- 授权 (Authorization) — 确定用户可以做什么的过程(角色、策略、声明)。
- 基于声明的身份 (Claims-based identity) — 一种方法,其中用户信息以一组声明(claims)的形式存储。
ASP.NET Core Identity
ASP.NET Core Identity 是一个完整的用户管理系统,包括注册、登录、密码重置、双因素身份验证和角色管理。它使用 Entity Framework Core 在数据库中存储数据。
要在项目中连接 Identity,只需添加 AddDefaultIdentity 调用并配置连接字符串。以下是 Program.cs 中的基本配置示例:
using Microsoft.AspNetCore.Identity;using Microsoft.EntityFrameworkCore;using YourApp.Data;
var builder = WebApplication.CreateBuilder(args);
// 添加数据库上下文builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// 添加 Identitybuilder.Services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; options.Password.RequireDigit = true; options.Password.RequiredLength = 6;}).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseAuthentication();app.UseAuthorization();
app.MapRazorPages();app.Run();之后,您将可以使用标准的注册和登录页面,以及用于检查角色的方法:
[Authorize(Roles = "Admin")]public IActionResult AdminPanel(){ return View();}JWT 身份验证 (JSON Web Tokens)
JWT 是一种紧凑且自包含的方式,以 JSON 对象的形式在各方之间传输信息。在 .NET 中,JWT 通常用于创建 REST API 和 SPA 应用程序。主要库是 Microsoft.AspNetCore.Authentication.JwtBearer。
在 Program.cs 中配置 JWT:
using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.IdentityModel.Tokens;using System.Text;
var builder = WebApplication.CreateBuilder(args);
var key = Encoding.ASCII.GetBytes("YourSuperSecretKeyThatIsAtLeast32CharactersLong!");
builder.Services.AddAuthentication(options =>{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(options =>{ options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "yourdomain.com", ValidAudience = "yourdomain.com", IssuerSigningKey = new SymmetricSecurityKey(key) };});
builder.Services.AddAuthorization();builder.Services.AddControllers();
var app = builder.Build();app.UseAuthentication();app.UseAuthorization();app.MapControllers();app.Run();示例