通八洲科技

Blazor AuthenticationStateProvider 使用教程

日期:2025-12-15 00:00 / 作者:煙雲
AuthenticationStateProvider是Blazor中广播用户认证状态的核心服务,需继承并重写GetAuthenticationStateAsync(),调用NotifyAuthenticationStateChanged通知UI更新,注册为Scoped(Server)或Singleton(WASM),配合CascadingAuthenticationState使用。

Blazor 的 AuthenticationStateProvider 是实现自定义身份验证逻辑的核心组件,它负责向整个应用提供当前用户的认证状态(比如是否已登录、用户身份信息等)。默认情况下,Blazor Server 和 Blazor WebAssembly 的基础模板已集成 Identity 或 JWT 认证,但若需对接自有登录系统、Token 存储在 localStorage、或需要手动触发状态刷新,你就得自定义一个 AuthenticationStateProvider

理解 AuthenticationStateProvider 的作用

它不是“做登录”的工具,而是“广播登录状态”的服务。Blazor 组件(如 AuthorizeViewAuthorizeRouteView)会订阅它的状态变更,从而动态显示/隐藏内容或跳转路由。它内部维护一个 Task,并通过 NotifyAuthenticationStateChanged 方法通知所有监听者状态已更新。

关键点:

手写一个基于 localStorage 的 Provider(WebAssembly 场景)

适用于 JWT 登录后把 token 存在浏览器 localStorage,页面刷新后仍需恢复登录态的场景。

步骤如下:

注意:WebAssembly 中无法直接访问 HttpContext,所以不能依赖服务端 Session;token 过期校验建议在每次请求前由 HttpClient 拦截器处理,而非全靠 Provider。

触发状态更新的正确方式

别在登录成功后只改内部字段就完事——UI 不会响应。必须调用 NotifyAuthenticationStateChanged

常见错误写法:

❌ this._currentUser = new ClaimsPrincipal(identity); // 不会刷新 UI

正确做法:

与路由和组件配合使用

确保 App.razor 中已包裹 CascadingAuthenticationState


  
    
      
      
    
    
      Not found
      
        

Sorry, there's nothing at this address.

之后你就能在任意组件中使用:

基本上就这些。不复杂但容易忽略 Notify 通知和生命周期注册时机,踩坑多在这两处。