ASP.NET Core 可以使用 Session cookie 来保护端点,确保只有授权用户才能访问受保护的内容。
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/" // 登录页面的路径
options.Cookie.Name = "MyCookie"; // cookie 名称
options.ExpireTimeSpan = TimeSpan.FromMinutes(30); // cookie 过期时间
});
[Authorize]
public IActionResult ProtectedEndpoint()
{
return View();
}
这将确保只有经过身份验证和授权的用户才能访问该端点。
var claims = new List
{
new Claim(ClaimTypes.Name, "Bob"),
new Claim(ClaimTypes.Email, "bob@example.com"),
new Claim(ClaimTypes.Role, "Admin"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30), // cookie 过期时间
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
以上示例代码会创建一个带有用户信息和过期时间的 cookie,该 cookie 会在用户登录成功后返回到客户端浏览器。其后,ASP.NET Core 会在每个请求中检查该 cookie 来验证用户身份。若用户已经通过身份验证,则端点将为其提供受保护的内容。若用户未通过身份验证,则将被重定向到登录页面。