在 Blazor Server 中,我们可以使用 ASP.NET Core 的身份验证和授权功能来实现基于 Cookie 的身份验证。我们可以在身份验证期间设置一个名为 LastUsername 的 Cookie,以便在下次登录时记住上一次登录的用户名。
以下是实现此过程的示例代码:
public void ConfigureServices(IServiceCollection services)
{
// ...其他配置
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.Name = "LastUsername";
});
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...其他配置
app.UseAuthentication();
app.UseAuthorization();
// ...其他配置
}
// 在登录页面或处理登录请求的处理程序中,以及成功验证页面中
var claims = new List
{
new Claim(ClaimTypes.Name, username)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
// 设置 LastUsername Cookie
HttpContext.Response.Cookies.Append("LastUsername", username);
var lastUsername = HttpContext.Request.Cookies["LastUsername"];
这样,我们就能够通过 Cookie 存储和获取上一次登录的用户名,为所有客户端设置上次登录的用户。