首页 > 解决方案 > 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。

显然,应用内导航和浏览器导航之间存在差异,但我不清楚我是否可以使用这个身份验证状态提供程序处理这两种类型。我该怎么办?有什么我缺少的吗?提前感谢帮助。

标签: c#jwt.net-5blazor-server-side

解决方案


推荐阅读