BlazorserversideCookieAuthentication-directlinkworkevenuserisnotauthenticated
创始人
2024-12-21 15:30:25
0

在Blazor服务端应用程序中,当使用Cookie Authentication时,直接访问受保护的页面链接时,即使用户未经过身份验证,仍会成功访问页面。 为解决此问题,可以在页面加载时进行身份验证。 在具有身份验证要求的组件中实现IAsyncDisposable接口,并在DisposeAsync()方法中取消订阅身份验证事件。

下面是示例代码:

@page "/protected"
@inject AuthenticationStateProvider AuthenticationStateProvider

@if(ViewModel.IsAuthenticated) {

You have access to the protected content!

} else {

You don't have permission to access the protected content.

}
@code { private AuthenticationState AuthenticationState => AuthenticationStateProvider.GetAuthenticationStateAsync().Result; private protectedViewModel ViewModel; protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); ViewModel = new protectedViewModel(authState.User); } protected override async ValueTask DisposeAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); ViewModel.Dispose(authState.User); await base.DisposeAsync(); } public class protectedViewModel : IAsyncDisposable { private readonly IDisposable _subscription; public protectedViewModel(ClaimsPrincipal user) { _subscription = user.Identity.IsAuthenticated ? null : NavigationManager.NavigateToTaskAsync("/login", true).ContinueWith(t => (IDisposable)null).Result; } public bool IsAuthenticated => _subscription == null; public async ValueTask DisposeAsync() { if (_subscription is not null) { await ((NavigationManager)services.GetRequiredService()).NavigateToAsync("/login", true); _subscription.Dispose(); } } } }

相关内容

热门资讯

第八分钟手段!微乐小程序辅助开... 第八分钟手段!微乐小程序辅助开挂(外挂)其实真的是有辅助教程(哔哩哔哩)1、微乐小程序辅助开挂破解器...
第4分钟项目!黑科技软件大全(... 第4分钟项目!黑科技软件大全(外挂)竟然是真的有辅助软件(哔哩哔哩);1、黑科技软件大全有没有辅助教...
6分钟模块!永胜联盟会封号吗(... 6分钟模块!永胜联盟会封号吗(外挂)切实真的是有辅助工具(哔哩哔哩)1、永胜联盟会封号吗有没有辅助教...
一分钟法子!青橙竞技辅助器怎么... 一分钟法子!青橙竞技辅助器怎么安装(外挂)好像存在有辅助脚本(哔哩哔哩)青橙竞技辅助器怎么安装能透视...
第八分钟要领!雀友会鱼虾蟹下载... 第八分钟要领!雀友会鱼虾蟹下载官网辅助器(外挂)原来有辅助教程(哔哩哔哩)一、雀友会鱼虾蟹下载官网辅...
第6分钟手筋!小程序跑得快的辅... 第6分钟手筋!小程序跑得快的辅助(外挂)总是是真的有辅助脚本(哔哩哔哩)1、上手简单,内置详细流程视...
第十分钟练习!陕西辅助(外挂)... 第十分钟练习!陕西辅助(外挂)竟然真的有辅助脚本(哔哩哔哩)1、实时陕西辅助透视辅助更新:用户可以随...
2分钟步骤!土豪辅助(外挂)都... 2分钟步骤!土豪辅助(外挂)都是存在有辅助攻略(哔哩哔哩)1、土豪辅助免费脚本咨询教程、土豪辅助免费...
五分钟积累!微信小程序家乡大贰... 五分钟积累!微信小程序家乡大贰破解版(外挂)原来存在有辅助技巧(哔哩哔哩)1、微信小程序家乡大贰破解...
3分钟技法!嘟咪互动修改器(外... 3分钟技法!嘟咪互动修改器(外挂)本来一直都是有辅助攻略(哔哩哔哩)1、玩家可以在嘟咪互动修改器线上...