【问题标题】:redirect user if not authenticated如果未通过身份验证,则重定向用户
【发布时间】:2021-06-19 00:41:51
【问题描述】:

我有一个 Blazor WASM 应用程序,其页面 (/upload) 只能由经过身份验证的用户访问。该页面标有@attribute [Authorize]

当我直接启动此页面并且没有用户登录时,一切都按预期工作(重定向到 root)。

但是当我使用菜单导航到页面之后用户在另一个浏览器选项卡中注销时页面被加载并且我在OnInitializedAsync()中的代码是由于没有用户登录而引发异常。导航是通过<NavLink ... >标签完成的

为什么用户没有被重定向到 root,我如何全局设置用户应该被重定向到 root(而不是每个页面)?

【问题讨论】:

    标签: asp.net-core blazor blazor-webassembly blazor-client-side


    【解决方案1】:

    这已经被问过了,但别担心,我知道了!更新您的 App.razor 页面以处理授权检查:

    <CascadingAuthenticationState>
        <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <NotAuthorized>
                        @if (context.User.Identity != null && !context.User.Identity.IsAuthenticated)
                        {
                            <RedirectToLogin />
                        }
                        else
                        {
                            <p>You are not authorized to access this resource.</p>
                        }
                    </NotAuthorized>
                    <Authorizing>
                        <Loader />
                    </Authorizing>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <div class="row justify-content-center">
                        <div class="col text-center">
                            <h2>Looks like you're lost, we didn't find anything at this location.</h2>
                            <p>Try navigating to the Dashboard or going back in the browser.</p>
                        </div>
                    </div>
                </LayoutView>
            </NotFound>
        </Router>
    </CascadingAuthenticationState>
    

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多