C# (.NET) 中的授权与身份验证:从基础到企业级解决方案
Web 应用程序的安全性是一个至关重要的开发环节,在 C# (.NET) 生态系统中,有一整套强大的工具用于实现身份验证(验证用户身份)和授权(验证访问权限)。本文将剖析关键方法:从内置的 ASP.NET Core Identity 到基于 JWT 和 OAuth 2.0 的灵活解决方案。
1. ASP.NET Core Identity — 内置用户管理系统
ASP.NET Core Identity 是一个完整的框架,用于注册、登录、角色和密码管理。它提供了现成的模型(User, Role)、存储(默认使用 Entity Framework + SQL Server)和中间件。
// 在 Program.cs 中注册builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDefaultIdentity<IdentityUser>(options =>{ options.SignIn.RequireConfirmedAccount = true; options.Password.RequiredLength = 8;}).AddRoles<IdentityRole>().AddEntityFrameworkStores<AppDbContext>();
// 中间件app.UseAuthentication();app.UseAuthorization();带保护的控制器示例:
[Authorize(Roles = "Admin")]public class AdminController : Controller{ public IActionResult Index() => View();}
// 获取当前用户var user = await _userManager.GetUserAsync(User);var roles = await _userManager.GetRolesAsync(user);2. JWT(JSON Web Token)— 适用于 API 和 SPA 的无缝身份验证
JWT 是一种紧凑的、URL 安全的令牌,包含关于用户的声明(claims)。非常适合 REST API、移动应用程序和单页应用程序(React, Angular, Vue)。
安装包:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer在 Program.cs 中的配置:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "https://pythonlib.ru", ValidateAudience = true, ValidAudience = "https://api.pythonlib.ru", ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes("SuperSecretKey123!SuperSecretKey123!")), ClockSkew = TimeSpan.Zero }; });生成令牌(例如,在登录控制器中):
var claims = new List<Claim>{ new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "User"), new Claim("custom_claim", "value")};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey123!"));var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken( issuer: "https://pythonlib.ru", audience: "https://api.pythonlib.ru", claims: claims, expires: DateTime.Now.AddHours(2), signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });保护端点:
[Authorize][HttpGet("profile")]public IActionResult GetProfile(){ var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; return Ok(new { Message = "访问已授权", UserId = userId });}3. Cookie 身份验证 — MVC 应用程序的经典方案
对于传统的服务器端应用程序(Razor Pages, MVC),使用 Cookie 身份验证非常方便。用户会收到一个加密的 Cookie,该 Cookie 会自动