Blazor tutorial for beginners - part 3
Blazor Server App 入門教學為主。Authentication.
How to add Authentication in Server-side Blazor | Blazor Tutorial 8
一般來說在 Blazor 都是使用 ideneity 做為登入認證。之前常用的表單驗證 FormsAuthentication 似乎已不再支援。
且會搭配 Microsoft.AspNetCore.Identity.UI包含適用于 ASP.NET Core 上之身分識別的 Razor Pages 內建 UI 類型。俱體上就是 Blazor 框架把登入認證與授權的UI都做好了,且半強迫的強制應用。
支援的指令有
AuthenticationStateProvider<CascadingAuthenticationState />@attribute [Authorize]<AuthorizeRouteView /><AuthorizeView Policy="..." Roles="..." /><Authorized /><Authorizing /><NotAuthorized />
一些範例碼
若登入認證機制完成,我們可以這樣下指令
@page
@attribute [Authorize]
<AuthorizeView>
<Authorized>
<p>@authState.User.Identit.Name</p>
<p>Page Content<p>
<Authorized>
<NotAuthorized>
<p>Sorry you cannot see this page.</p>
<NotAuthorized>
</AuthorizeView>
@code{
[CascadingParameter]
private AuthenticationState authState {get; set;}
}<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<Authorizing>
<h1>Just a second</h1>
<p>You are bging authorized</p>
<Authorizing>
<NotAuthorized>
<h1>Sorry</h1>
<p>You cannot see this bye bye</p>
</NOtAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Authorization in Server-Side Blazor | Blazor Tutorial 9
Authentication = Who you are
Authorization = What you can do
Default Authentication
User is in role
User has claim
Police is satisfied
練習比較重要。下面為 Roles, Policy 的範例部份截錄
@page
<AuthorizeView Policy="IsAdmin">
<Authorized>
...
</Authorized>
</AuthorizeView>
<AuthorizeView Roles="SecretRole">
<Authorized>
...
</Authorized>
</AuthorizeView>
Blazor identity 登入認證的資料很多。不過方法都一樣,開專案時直接加入identity認證機制後再改寫。
How to use HTML5 Web Storage in Blazor | Blazor Tutorial 10
請直接參考下面附件。
下面二個模組:Blazored/SessionStorage, Blazored/LocalStorage 可用於 Blazor WASM App,但不適合用於 Blazor Server App。Blazor Server App 直接使用預設的 ProtectedSessionStorage、ProtectedLocalStorage會更好。
Managing Blazor state using Redux | Blazor Tutorial 11
疑問?Redux 應該只適用於 Blazor WASM App 模式才對吧?經測試在二種模式下皆可運作,不過在 Blazer Server App 模式下並不需要 Redux。 應該用 C#9 record type 記錄類型 實作 State,因為前端的狀態是 immutable。
在 Blazor Server App 模式下並不需要 Flux/Redux 。在 Blazor WASM App 模式下若前端資料很多的話就可以考慮加入 Flue/Redux 。
一個推薦方案:Fluxor
Install-Package Fluxor
Install-Package Fluxor.Blazor.Web
Install-Package Fluxor.Blazor.Web.ReduxDevTools補充:一些進階文章整理
Last updated

