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

Blazor项目OpenIdConnect认证排除Error Razor页面解决无限跳转问题

解决方法

你出现无限跳转的核心原因是全局配置了所有请求都需要身份验证,/error路径也被包含在校验范围内,未登录用户访问会被再次重定向到登录页形成循环,按以下步骤修改即可:


步骤1:给Error.razor添加允许匿名访问特性

直接在Error.razor的顶部添加[AllowAnonymous]标记,跳过该页面的身份校验:

@page "/error"
@attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous]
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
    Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
    <strong>The Development environment shouldn't be enabled for deployed applications.</strong>
    It can result in displaying sensitive information from exceptions to end users.
    For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
    and restarting the app.
</p>

步骤2:调整全局授权规则,排除error路径

你当前在AddControllersWithViews中加了全局授权过滤器,同时还要针对Razor Pages和Blazor的路由做排除配置,修改ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
{
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables()
        .Build();

    services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    });

    // 新增:配置Razor Pages路由,/Error路径允许匿名访问
    services.AddRazorPages(options =>
    {
        options.Conventions.AllowAnonymousToPage("/Error");
    });
    
    services.AddServerSideBlazor();
    
    services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));


    services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false
        };

        options.Events = ConfigureOpenIdConnectEvents(services);
        
        // 可选:新增登录跳转拦截逻辑,error路径直接返回401不跳转登录页
        options.Events.OnRedirectToLogin = context =>
        {
            if (context.Request.Path.StartsWithSegments("/error", StringComparison.OrdinalIgnoreCase))
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return Task.CompletedTask;
            }
            context.Response.Redirect(context.RedirectUri);
            return Task.CompletedTask;
        };
    });
}

步骤3:(可选)校验端点配置

如果是Startup模式的项目,确保Configure方法的端点配置中没有给/error路径加全局授权规则:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其余原有中间件配置保持不变
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapBlazorHub();
        endpoints.MapRazorPages();
        endpoints.MapControllers();
        endpoints.MapFallbackToPage("/_Host");
        // 显式给/error路由允许匿名
        endpoints.Map("/error", async context =>
        {
            await context.Response.WriteAsync("");
        }).AllowAnonymous();
    });
}

修改完成后重启项目即可,错误页无需登录就能正常访问,不会再出现跳转死循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:06:03