c# - Blazor 自定义身份验证状态提供程序不适用于 AuthorizeRouteView
问题描述
我们在 Blazor Server 应用程序中实现了一个自定义身份验证状态提供程序,以检索和验证用户的 JWT。如下:
public class CustomAuthStateProvider : AuthenticationStateProvider
{
private ITokenService TokenService;
private TokenValidationParameters Validations;
public CustomAuthStateProvider(ITokenService tokenService, TokenValidationParameters validations)
{
TokenService = tokenService;
Validations = validations;
}
public async override Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var token = TokenService.TryGetToken();
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(token, Validations, out var _);
var identity = string.IsNullOrEmpty(token)
? new ClaimsIdentity()
: new ClaimsIdentity(ServiceExtensions.ParseClaimsFromJwt(token), "JWT");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
catch (Exception e)
{
var identity = new ClaimsIdentity();
return new AuthenticationState(new ClaimsPrincipal(identity));
};
}
}
App.razor 文件的布局如下:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<UnauthorizedRedirect />
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p class="text-muted text-center">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
<UnauthorizedRedirect />
在这种情况下,是一个自定义组件,它根据用户是否经过身份验证做出不同的响应。这样就不会将已登录但尝试访问受限资源的用户重定向到登录屏幕。
整个设置工作正常,直到用户的令牌过期。此时,令牌验证失败,异常被捕获,并且身份验证状态提供程序返回空白身份验证状态,但应用程序没有将用户重定向到登录屏幕,而是完全不做任何事情,让用户可以自由浏览整个应用程序,直到他们刷新屏幕或故意在浏览器中键入新 URL。
显然,应用内导航和浏览器导航之间存在差异,但我不清楚我是否可以使用这个身份验证状态提供程序处理这两种类型。我该怎么办?有什么我缺少的吗?提前感谢帮助。
解决方案
推荐阅读
- paypal-sandbox - While subscribe a user I got eror code 91927 in braintree using node js
- c - 使用指针打印二维数组时出错
- angular - 具有嵌套对象的 Angular Material 中的默认排序
- android - 发布多个 MutableLiveData 没有顺序
- python - 按数据分组到详细数据
- javascript - 我的代码有什么问题 - 它没有关闭
- php - 在 PHP 中访问 MySQL 存储过程的返回值
- java - 是否支持使用 java 库“javers”比较功能对 SortedSet 进行更改?
- javascript - Vue - 通过 vue 组件传递 prop 数组会导致未定义的错误
- java - 在集合的每个元素上调用函数