ASP.NET UseAuthentication
最后修改于 2025 年 4 月 3 日
在本文中,我们将探讨 ASP.NET 8 中的 UseAuthentication 中间件。此中间件对于在 Web 应用程序中实现身份验证至关重要。
ASP.NET 提供了一个强大的身份验证系统,支持各种提供程序。UseAuthentication 在请求管道中启用身份验证中间件。
基本定义
UseAuthentication 是 ASP.NET 中的一个中间件组件,它启用身份验证功能。它必须在任何依赖于用户已通过身份验证的中间件之前调用。
身份验证是确定用户身份的过程。ASP.NET 支持基于 cookie 的身份验证、JWT、OAuth 和其他身份验证方案。
UseAuthentication 与通过 AddAuthentication 注册的身份验证服务配合使用。它会检查每个请求的身份验证凭据。
ASP.NET UseAuthentication 示例
以下示例演示了使用 UseAuthentication 的基于 cookie 的身份验证。
var builder = WebApplication.CreateBuilder(args);
// Add authentication services
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
// Enable authentication middleware
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
这会设置基于 cookie 的身份验证,并为登录和访问被拒绝设置自定义路径。UseAuthentication 中间件放置在路由之后、授权之前。
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string returnUrl = "/")
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
public async Task<IActionResult> Login(string username, string password, string returnUrl)
{
if (username == "admin" && password == "password")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "Administrator")
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));
return LocalRedirect(returnUrl);
}
ViewData["ReturnUrl"] = returnUrl;
ModelState.AddModelError("", "Invalid username or password");
return View();
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
}
AccountController 负责登录和注销操作。Login 操作会验证凭据并创建一个包含声明的 cookie。Logout 操作会删除身份验证 cookie。
@{
ViewData["Title"] = "Login";
}
<h2>Login</h2>
<form method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<input type="hidden" name="returnUrl" value="@ViewData["ReturnUrl"]" />
<button type="submit">Login</button>
</form>
@if (ViewData.ModelState[""]?.Errors.Count > 0)
{
<div class="error">
@Html.ValidationSummary()
</div>
}
这个简单的登录视图收集用户名和密码。它包含验证消息,并保留 return URL 以便在成功登录后重定向。
该示例演示了一个完整的身份验证流程。UseAuthentication 中间件会在每次请求时处理身份验证 cookie。[Authorize] 属性可以保护控制器操作。
来源
在本文中,我们探讨了 ASP.NET 8 中的 UseAuthentication 中间件。此基本组件可在 Web 应用程序中实现安全的身份验证。