在 Blazor Web Assembly 中的令牌过期时间自动注销

Logout automatically on token expiration time in blazor web assembly

我正在开发一个 Blazor Web 程序集应用程序。我创建了登录和注销方法,为了在令牌过期时间注销,我将过期日期存储在本地存储中。但检查此日期需要加载整页。我想自动检查该日期,或者当我打开一个页面并在该时间过去时重定向到登录页面。

这是我的CustomAuthenticationStateProvider.cs

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorageService;

    public CustomAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorageService)
    {
        _httpClient = httpClient;
        _localStorageService = localStorageService;
    }

    private async Task<bool> TokenExpired()
    {
        bool expire = false;

        var exist = await _localStorageService.ContainKeyAsync(ClientConstantKeys.AppTokenExpireDate);

        if (exist)
        {
            var dateString = await _localStorageService.GetItemAsync<string>(ClientConstantKeys.AppTokenExpireDate);
            var date = DateTime.Parse(dateString);

            if (DateTime.Now >= date)
            {
                expire = true;
                await NotifyUserLoggedOut();
            }
        }
        else
        {
            expire = true;
            await NotifyUserLoggedOut();
        }

        return expire;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var token = await _localStorageService.GetItemAsync<string>(ClientConstantKeys.AppToken);
        var expired = await TokenExpired();

        if (string.IsNullOrEmpty(token) || expired)
        {
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        }

        var claimsValueTypes = await _localStorageService.GetItemAsync<Dictionary<string, object>>(ClientConstantKeys.AppClaims);
        var claims = ClaimParser.GetClaims(claimsValueTypes);

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);


        return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwtAuthType")));
    }

    public void NotifyUserLogIn(List<Claim> claims)
    {
        var authState = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwtAuthType"))));
        base.NotifyAuthenticationStateChanged(authState);
    }

    public async Task NotifyUserLoggedOut()
    {
        var authState = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
        await _localStorageService.RemoveItemAsync(ClientConstantKeys.AppToken);
        await _localStorageService.RemoveItemAsync(ClientConstantKeys.AppClaims);
        await _localStorageService.RemoveItemAsync(ClientConstantKeys.AppTokenExpireDate);
        _httpClient.DefaultRequestHeaders.Authorization = null;
        base.NotifyAuthenticationStateChanged(authState);
    }
}

这是App.Razor

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
              <AccessDenied></AccessDenied>
            </NotAuthorized>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <PageNotFound></PageNotFound>
        </LayoutView>
    </NotFound>
</Router>
</CascadingAuthenticationState>

当我点击登录或注销时一切正常,但我想自动检查过期时间。

我尝试用 AuthorizedView 标记包裹我的整个页面,但没有任何反应。

谢谢

我使用 FilterPipeline 检查令牌过期时间,然后在每次请求后检查 Blazor WASM 上的响应类型。制作了一个使代码干净的功能。方法如下:

网页API->过滤器->JwtTokenValidateAttribute.cs

 public class JwtTokenValidateAttribute : Attribute, IAuthorizationFilter
    {

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            string token = context.HttpContext.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
            if (string.IsNullOrWhiteSpace(token))
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            var tokenManager = context.HttpContext.RequestServices.GetService(typeof(ICustomTokenManager)) as ICustomTokenManager;
            if(tokenManager != null && !tokenManager.VerifyToken(token))
            {
                context.Result = new UnauthorizedResult();
                return;
            }
        }
    }

在我们创建属性后,我们可以像这样在控制器上调用它:

 [Route("api/[controller]")]
    [ApiVersion("1.0")]
    [ApiController]
    [JwtTokenValidateAttribute] //here we call the filter pipeline
    public class SupplierCompaniesController : ControllerBase
    {
       //your controller goes here
    }

MainLayout.razor:

@code{
 public async Task HandleException(Exception exception)
    {
        if (exception.Message.Contains("401"))
        {
            await AuthenticationUseCases.Logout();
            navigationManager.NavigateTo("/login/Expired", true);
            return;
        }
//If you use AutoWrapper or other packages, you can send messages here based on your response type, don't forget to parse the values. 
    }
}

之后我们可以在我们向 API 发送请求的任何页面中调用 HandleErrors,示例:

首先我们需要用CascadingValue包裹@body

<CascadingValue Value="this" Name="MainLayout">
     @Body
</CascadingValue>

现在我们需要转到我们要向 API

发送请求的任何 Razor 组件
@code{
[CascadingParameter(Name = "MainLayout")]
public MainLayout MainLayout { get; set; }
async Task HandleException(Exception e) => await MainLayout.HandleException(e);

async Task OnCreateRow(RoleDto role)
    {
        try
        {
            //Your api call goes here
        }
        catch (Exception e)
        {
            await MainLayout.HandleException(e);
        }
    }
}

这个解决方案可能不是最好的,希望对您有所帮助。