You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

托管于ASP.NET Core的预渲染Blazor WASM项目OIDC认证报错求助

问题原因

你在服务端同时注册了仅适用于Blazor Server的ServerAuthenticationStateProvider和仅适用于Blazor WASM客户端的远程认证服务,预渲染阶段代码运行在服务端上下文,ServerAuthenticationStateProvider没有实现WASM的IRemoteAuthenticationService接口,因此触发类型转换异常。

解决方案

1. 移除服务端错误注册的认证服务

删除Startup.cs ConfigureServices方法中的两行代码:

// 删除这两行
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>().AddScoped<SignOutSessionStateManager>();
services.AddRemoteAuthentication<RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>();

上述服务应该在Blazor WASM客户端项目的Program.cs中注册,不属于服务端预渲染的服务配置。

2. 实现预渲染专用的认证状态提供器

预渲染阶段需要从服务端的Cookie认证上下文获取当前登录用户信息,自定义适配预渲染场景的AuthenticationStateProvider:

using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

public class PrerenderingAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PrerenderingAuthenticationStateProvider(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var user = _httpContextAccessor.HttpContext?.User ?? new ClaimsPrincipal();
        return Task.FromResult(new AuthenticationState(user));
    }
}

然后在Startup.cs中注册相关服务:

services.AddHttpContextAccessor();
services.AddScoped<AuthenticationStateProvider, PrerenderingAuthenticationStateProvider>();

3. 调整中间件顺序

当前你配置的中间件顺序错误,UseIdentityServer需要放在UseAuthentication之后、UseAuthorization之前,修改Configure方法:

app.UseRouting();
app.UseStaticFiles();
app.UseBlazorFrameworkFiles();

app.UseAuthentication();
app.UseIdentityServer(); // 移动到此处
app.UseAuthorization();

4. 同步预渲染用户状态到WASM客户端

在Client.cshtml页面将服务端获取到的用户声明序列化传递给Blazor客户端,避免WASM加载后重复触发认证流程:

@{
    var initialUserClaims = System.Text.Json.JsonSerializer.Serialize(User.Claims.Select(c => new { c.Type, c.Value }));
}
<component type="typeof(PrettyNotes.Web.Client.App)" render-mode="WebAssemblyPrerendered" param-InitialUserClaims="@initialUserClaims"/>

之后在客户端App.razor中接收InitialUserClaims参数,在WASM认证服务初始化时同步用户状态即可。

相关学习资源
  • Blazor WASM预渲染场景下的身份认证最佳实践官方文档
  • 包含OIDC集成、预渲染用户状态同步的完整Blazor示例代码仓库
  • ASP.NET Core Identity 结合 Blazor WASM 预渲染的全流程实现教程

内容的提问来源于stack exchange,提问作者AlexeyBobrovich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:24:04