Blazor 安全性 - Razor 页面自定义 authentication/security

Blazor Security - Razor Pages custom authentication/security

我正在尝试构建一个托管在服务器上的 Blazor 应用程序,起点在剃刀页面内。 类似的东西:

<component type="typeof(Main)" render-mode="ServerPrerendered" param-Data="@simple"/>

我的问题是:

大致情况:

@if (HasPermission)
{
   <button type="button" onclick="MutateDatabase">MutateDatabase</button>
}

我假设你 运行 Blazor 服务器(在撰写本文时 WASM 仍处于预览阶段,在安全方面会有很大不同)。

documentataion 声明 Blazor 确实与 ASP.NET 核心身份集成:

Blazor Server apps include a built-in AuthenticationStateProvider service that obtains authentication state data from ASP.NET Core's HttpContext.User. This is how authentication state integrates with existing ASP.NET Core server-side authentication mechanisms.

现在,回答您的问题:

  1. 给定您的呈现模式,要让 Blazor 启动,Razor 页面必须呈现初始状态并标记 Blazor 稍后要在其中管理视图的元素。方式AuthorizeAttribute works (I presume this is what you meant?) will block the page from rendering, so this should prevent Blazor from starting altogether - you will get redirected away to authenticate. Once your users are past that gate though - be aware that Blazor handles [Authorize] on child controls differently

    Only use [Authorize] on @page components reached via the Blazor Router. Authorization is only performed as an aspect of routing and not for child components rendered within a page. To authorize the display of specific parts within a page, use AuthorizeView instead.

    (这似乎不是你的情况,但我把它放在这里以防万一)

  2. 我不太确定我是否理解这里的声明:circuit is the term MS uses to identify the slice of server where your application instance lives while it's displayed to a client. The connection is maintained via websockets and is generally scoped to a session (check out cookies and url parameters to your /_blazor endpoint). The user is however not guaranteed to have same circuit throughout application lifetime (due to connection issues or server load-balancer config) - and it is fine, you are expected to handle state persistance across circuits 你自己。

  3. 我认为这种情况与 (1) 相同:在呈现托管 Razor 视图之前,您不会启动 Blazor。
  4. 可能最好遵循 Blazor 的 security management page:您有几个选项可以确保您为经过身份验证的用户提供服务:

    1. 使用 <AuthorizeView> 控制呈现的内容:

    <AuthorizeView>
    <Authorized>
        <button type="button" onclick="MutateDatabase">MutateDatabase</button>
    </Authorized>
    <NotAuthorized>
        <p>You're not signed in.</p>
    </NotAuthorized>
    </AuthorizeView>
    

    从技术上讲,您可以使用 if (user.IsInRole()) 语句,但 might not get updated when User AuthenticationState changes

    如果这还不够,您可以 pick up cascading AuthenticationState parameter or look at implementing your own AuthenticationStateProvider