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(); } } } }

相关内容

热门资讯

透视好牌!aapoker万能辅... 透视好牌!aapoker万能辅助器(透视)免费透视脚本(一贯是真的有挂)1、首先打开aapoker万...
透视透视挂!aapoker真的... 透视透视挂!aapoker真的假的(透视)辅助插件工具(真是是有挂)1)aapoker真的假的辅助挂...
透视脚本!aa poker辅助... 透视脚本!aa poker辅助(透视)万能辅助器(其实有挂);1、下载好aa poker辅助辅助软件...
透视好友!aapoker插件下... 透视好友!aapoker插件下载(透视)透视脚本入口(一直真的有挂);1、玩家可以在aapoker插...
透视辅助!aapoker脚本(... 透视辅助!aapoker脚本(透视)透视脚本(一直是真的有挂);1、实时aapoker脚本开挂更新:...
透视中牌率!aapoker免费... 透视中牌率!aapoker免费透视脚本(透视)辅助插件工具(都是真的有挂);1、aapoker免费透...
透视肯定!aapoker真的假... 透视肯定!aapoker真的假的(透视)透视方法(一贯真的有挂)aapoker真的假的是一种具有地方...
透视辅助!aapoker透视怎... 透视辅助!aapoker透视怎么用(透视)透视脚本下载(确实真的是有挂)1、进入到aapoker透视...
透视玄学!aapoker如何设... 透视玄学!aapoker如何设置胜率(透视)透视脚本(确实是真的有挂);1.aapoker如何设置胜...
透视ai代打!aapoker透... 透视ai代打!aapoker透视脚本(透视)ai插件(一贯是有挂);1、任何aapoker透视脚本a...