Blazor WASM App 驗證與授權

參考文章

Blazor Webassembly Custom Authentication [Blazor Tutorial C# - Part 12]

進階閱讀

原來之前已寫過了~哈哈

關鍵知識

大概八成以上的方法或程式碼在 Blazor Server App 也互通。但也請別忘了他們兩的基本特性是不同的。

在 Program.cs (或 Startup.cs) 註冊 AuthenticationStateProvider 時用 Singleton 否則 AuthenticationState 登入狀態只有在 page 載入時才會觸發更新。

開發環境

平台:.NET6 IDE: Visual Studio 2022 骨架: Blazor WASM App

關鍵程式碼 - 註冊 AuthenticationStateProvider

在 Program.cs (或 Startup.cs) 註冊 AuthenticationStateProvider 時用 Singleton 否則登入狀態 AuthenticationState只有在 page 載入時才會觸發畫面更新,誤以為 NotifyAuthenticationStateChanged() 通告無效。

Client\Program.cs
[...略...]
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

//## for Authz.
builder.Services.AddSingleton<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
builder.Services.AddAuthorizationCore();

[...略...]
await builder.Build().RunAsync();

(EOF)

Last updated