Blazor Server框架支持使用cookie进行身份验证。默认情况下,它使用的是Identity作为AuthenticationScheme。然而,您也可以自定义AuthenticationScheme并使用自定义的cookie名称和选项。以下是使用自定义AuthenticationScheme的示例代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = "MyCustomAuthScheme";
})
.AddCookie("MyCustomAuthScheme", options =>
{
options.Cookie.Name = "MyCustomCookieName";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
@page "/"
@attribute [Authorize(AuthenticationSchemes = "MyCustomAuthScheme")]
Hello, @context.User.Identity.Name!
@code {
[CascadingParameter]
private Task authenticationStateTask { get; set; }
private ClaimsPrincipal _user;
protected override async Task OnInitializedAsync()
{
var authState = await authenticationStateTask;
_user = authState.User;
}
private AuthenticationProperties SetToken(string key, string value)
{
return new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(7),
Items =
{
{ key, value }
}
};
}
private async Task LoginUser()
{
var claims = new List
{
new Claim(ClaimTypes.Name, "testuser"),
new Claim(ClaimTypes.Role, "admin")
};
var identity = new ClaimsIdentity(claims, "MyCustomAuthScheme");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("MyCustomAuthScheme", principal, SetToken("testkey", "testvalue"));
_user = principal;
StateHasChanged();
}
private async Task LogoutUser()
{
await HttpContext.SignOutAsync("MyCustomAuthScheme");
上一篇:BlazorServercontentpagelifecycleexecutedearlierthanlayout
下一篇:BlazorServer错误aspnetcore-browser-refresh.js:234:WebSocket连接到'wss://localhost:56871/'失败