You need to enable JavaScript to run this app. Blazor WebAssembly实现token过期自动登出功能的咨询
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WebAssembly实现token过期自动登出功能的咨询

解决方案

核心问题说明

你当前的过期检测逻辑仅在GetAuthenticationStateAsync被调用时触发,而Blazor默认仅在页面首次加载、手动调用NotifyAuthenticationStateChanged时才会执行该方法,路由跳转、用户停留在当前页面时都不会主动触发检测。

实现步骤

1. 修复时区检测误差(必改)

如果后端返回的token过期时间为UTC格式(行业通用规范),使用DateTime.Now会因为时区差异导致检测错误,修改TokenExpired方法中的时间对比逻辑:

// 原代码
if (DateTime.Now >= date)
// 替换为
if (DateTime.UtcNow >= date)

同时保证你存储AppTokenExpireDate时统一用UTC格式的字符串。

2. 路由跳转时自动触发检测

修改App.razor,给Router组件添加OnNavigateAsync回调,每次页面跳转都会主动执行过期检测:

@inject AuthenticationStateProvider AuthStateProvider

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true" OnNavigateAsync="OnNavigateAsync">
    <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>

@code {
    private async Task OnNavigateAsync(NavigationContext args)
    {
        // 主动拉取认证状态,触发过期检测逻辑
        await AuthStateProvider.GetAuthenticationStateAsync();
    }
}

3. 后台定时检测(可选,解决用户停留在同一页面的场景)

修改CustomAuthenticationStateProvider,添加定时器定期检测token状态,实现无操作时的自动过期登出:

public class CustomAuthenticationStateProvider : AuthenticationStateProvider, IDisposable
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorageService;
    private readonly NavigationManager _navManager;
    private Timer _tokenCheckTimer;
    private readonly CancellationTokenSource _cts = new();

    public CustomAuthenticationStateProvider(HttpClient httpClient, 
        ILocalStorageService localStorageService,
        NavigationManager navManager)
    {
        _httpClient = httpClient;
        _localStorageService = localStorageService;
        _navManager = navManager;
        // 每1分钟检测一次,可自行调整间隔时长
        _tokenCheckTimer = new Timer(CheckTokenExpired, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
    }

    private async void CheckTokenExpired(object state)
    {
        if (_cts.IsCancellationRequested) return;
        await TokenExpired();
    }

    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);
        // 登出后自动跳转到登录页,替换为你实际的登录路由
        _navManager.NavigateTo("/login");
    }

    public void Dispose()
    {
        _cts.Cancel();
        _tokenCheckTimer?.Dispose();
        _cts.Dispose();
    }

    // 其余原有代码保持不变
}

记得在Program.cs中按以下格式注册服务,保证依赖注入正常:

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();

4. 可选优化:接口401拦截

给HttpClient添加委托拦截器,当接口返回401状态码时直接触发登出,解决token被篡改、提前失效的场景:

public class AuthHttpHandler : DelegatingHandler
{
    private readonly CustomAuthenticationStateProvider _authProvider;
    public AuthHttpHandler(CustomAuthenticationStateProvider authProvider)
    {
        _authProvider = authProvider;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        {
            await _authProvider.NotifyUserLoggedOut();
        }
        return response;
    }
}

在Program.cs中注册该拦截器即可。


内容的提问来源于stack exchange,提问作者Abolfazl Davoodi Shandiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:06:00