在 blazor Web 程序集中的令牌到期时间自动注销

时间:2021-06-05 18:30:14

标签: c# asp.net-web-api blazor blazor-webassembly

我正在开发一个 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 标签包裹我的整个页面,但没有任何反应。

谢谢

0 个答案:

没有答案