服务器端 Blazor 中会话超时重定向

3

看起来Blazor目前不支持通过滑动过期机制检查因不活动而导致的身份验证超时。

我想要实现的是一旦用户的会话时间结束就重定向到登录页面。我可以想象必须在RevalidatingIdentityAuthenticationStateProvider中检测站点上的活动并在会话超时时将用户重定向到登录页面,但不确定如何实现这一点?

1个回答

1

您实际上不需要使用

RevalidatingIdentityAuthenticationStateProvider

来验证您的应用程序。您的 app.razor 只需要像这样的代码:

<CascadingAuthenticationState> 
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" 
                     DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    **<RedirectToLogin> </RedirectToLogin>**
                </NotAuthorized>
                <Authorizing>
                    <h1>Authentication in progress</h1>
                    <p>Only visible while authentication is in progress.</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
           ....
        </NotFound>
    </Router>
</CascadingAuthenticationState>

确保RedirectToLogin组件在OnAfterRender回调中重定向用户,应该看起来像这样:
 [CascadingParameter]
    private Task<AuthenticationState> AuthenticationStateTask { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
      {
        var authenticationState = await AuthenticationStateTask;
        try
        {
            if (authenticationState?.User?.Identity is null || !authenticationState.User.Identity.IsAuthenticated)
                {
                    var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);

                    if (string.IsNullOrWhiteSpace(returnUrl))
                        Navigation.NavigateTo("/Identity/Account/Login", true);
                    else
                        Navigation.NavigateTo($"/Identity/Account/Login?returnUrl=~/{returnUrl}", true);
                }
        }
        catch (Exception e)
        {

            
        }
       
    }

1
想知道您的代码如何实现请求的不活动超时目标?您的重定向测试是查找authenticationState?.User?.Identity是否为空,但在您的示例中,authenticationState从未设置为null。那么,这将如何导致X分钟不活动后注销/重定向? - Joseph R
1
PS:我的问题也一样,所以我来这里寻找灵感 :-) - Joseph R
我真的不太记得这个答案了,但我猜我的想法是发行一个令牌,在有效时间内用户无需进行身份验证。 - Nour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接