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

未认证时Blazor onclick失效,AllowAnonymous页面仍报CORS错误

问题分析与解决方案

你的问题核心是:Blazor Server应用配置Azure AD可选认证后,未认证用户点击按钮触发CORS错误,本质是认证中间件在未认证状态下自动尝试重定向到Azure AD登录端点,而浏览器将该请求判定为跨域请求,导致CORS拦截。以下是具体修复步骤:

1. 调整认证中间件配置,禁止自动重定向未认证请求

在Program.cs中,配置Azure AD认证选项,取消未认证请求的自动重定向,并跳过无法识别的请求,避免Blazor初始化时触发不必要的身份验证跳转:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

// 配置OpenIdConnect选项,禁用自动重定向
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    // 禁止未认证请求自动跳转到登录页
    options.AutomaticRedirectToLoginPath = false;
    // 跳过无法识别的请求,避免中间件处理Blazor的SignalR初始化请求
    options.SkipUnrecognizedRequests = true;
});

2. 确保Blazor核心端点允许匿名访问

在Program.cs的端点配置中,明确允许匿名用户访问Blazor Hub和_Host页面:

app.UseEndpoints(endpoints =>
{
    endpoints.MapBlazorHub().AllowAnonymous();
    endpoints.MapFallbackToPage("/_Host").AllowAnonymous();
    endpoints.MapControllers().RequireAuthorization(); // 控制器接口按需授权
});

3. 恢复AuthorizeRouteView实现可选认证

不要全局替换为RouteView,而是通过AuthorizeRouteView实现页面级的权限控制,这样未认证用户可以访问无授权要求的页面,需要认证的页面则会触发登录引导:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">   
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <p>您需要登录才能使用此功能,请<a href="MicrosoftIdentity/Account/SignIn">点击登录</a></p>
                </NotAuthorized>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <PageTitle>页面未找到</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">抱歉,该地址不存在内容。</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

4. 按需添加授权属性

在需要限制访问的页面或组件上添加[Authorize]属性,无需认证的页面保持默认或添加[AllowAnonymous]:

@page "/secure-page"
@attribute [Authorize]

<!-- 仅认证用户可见的内容 -->

问题根源解释

你之前的配置中,全局替换AuthorizeRouteView为RouteView并在_Host.cshtml添加[AllowAnonymous],虽然允许页面加载,但认证中间件仍会在Blazor的SignalR连接初始化过程中尝试对未认证用户发起重定向到Azure AD。由于该重定向请求是浏览器端发起的跨域请求,而Azure AD的登录端点不会为你的本地开发域名添加Access-Control-Allow-Origin头,因此触发CORS错误。通过禁用自动重定向并正确配置路由授权,可以避免这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:02:04