用途:为 Blazor Web App 添加身份验证与授权,并按应用的渲染模式(静态 SSR、Server、WebAssembly、Auto)做对应处理。
主要能力:在 Program.cs 注册认证与授权服务、接入 ASP.NET Core Identity;在 App.razor 用 AuthorizeRouteView 并按页面条件应用渲染模式;在页面上用 [Authorize](支持 Roles、Policy);用 AuthorizeView 控制 UI 显示,并通过 [CascadingParameter] Task<AuthenticationState> 在代码中读取认证状态;在 WebAssembly/Auto 模式下通过 AddAuthenticationStateSerialization / AddAuthenticationStateDeserialization 传递认证状态。
必要用法:先读工作区根目录的 AGENTS.md 确认交互模式与范围;服务端注册 AddCascadingAuthenticationState()、AddAuthorization(),Identity 需 AddAuthentication().AddIdentityCookies()、AddIdentityCore<ApplicationUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddSignInManager().AddDefaultTokenProviders();App.razor 需用 AcceptsInteractiveRouting() 判断返回渲染模式或 null。
限制:SignInManager 与 UserManager 依赖 HttpContext,在交互组件中会抛异常,Identity 页面必须保持静态 SSR;全局交互应用需给每个 Identity 页面加 [ExcludeFromInteractiveRouting];静态 SSR 下 <NotAuthorized> 不生效,需用中间件重定向;WebAssembly/Auto 无 HttpContext,缺少序列化注册会导致匿名用户;交互组件应使用 Task<AuthenticationState> 而非 HttpContext.User。