BlazorServercookieauthenticationwithcustomAuthenticationScheme
创始人
2024-12-21 15:00:09
0

Blazor Server框架支持使用cookie进行身份验证。默认情况下,它使用的是Identity作为AuthenticationScheme。然而,您也可以自定义AuthenticationScheme并使用自定义的cookie名称和选项。以下是使用自定义AuthenticationScheme的示例代码:

  1. 在Startup.cs中定义自定义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";
});
  1. 使用认证的自定义cookie:
@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");

相关内容

热门资讯

推荐一款(中至常熟麻将技巧)本... 您好,中至常熟麻将技巧这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
盘点几款(天天贵阳手机麻将通用... 盘点几款(天天贵阳手机麻将通用胡牌神器)往昔真的有挂(辅助挂)2025版教程(2026已更新)(哔哩...
一分钟教你(豆豆斗牌辅助器)确... 一分钟教你(豆豆斗牌辅助器)确实是有挂(辅助挂)揭秘教程(2021已更新)(哔哩哔哩);豆豆斗牌辅助...
一分钟快速了解(手机唯思竞技麻... 一分钟快速了解(手机唯思竞技麻将有挂)起初真的是有挂(辅助挂)技巧教程(2022已更新)(哔哩哔哩)...
最新研发(浙江游戏大厅插件)先... 您好,浙江游戏大厅插件这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
必知教程(大盘山棋牌有挂)好像... 必知教程(大盘山棋牌有挂)好像存在有挂(辅助挂)详细教程(2025已更新)(哔哩哔哩);大盘山棋牌有...
重磅来袭(山西大唐麻将系统规律... 重磅来袭(山西大唐麻将系统规律)确实是真的有挂(辅助挂)细节揭秘(2021已更新)(哔哩哔哩);超受...
大神推荐(哈哈长沙麻将可以提高... 大神推荐(哈哈长沙麻将可以提高胜率)总是有挂(辅助挂)揭秘教程(2023已更新)(哔哩哔哩);1、选...
发现一款(大齐山东麻将有挂)确... 您好,大齐山东麻将有挂这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家在...
分享一款(浙江游戏大厅游戏外挂... 【福星临门,好运相随】;分享一款(浙江游戏大厅游戏外挂)往昔存在有挂(辅助挂)透牌教程(2021已更...