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

Azure B2C配置后.NET 8 Razor Pages始终重定向至错误页问题

.NET 8 Razor Pages Azure AD B2C认证重定向404错误排查与解决

问题描述

搭建了一个.NET 8 Razor Pages测试应用,计划通过Azure B2C租户实现身份认证。已在Program.cs中配置Azure AD B2C,并为所有页面添加全局授权规则,预期未认证用户会跳转至登录页,但实际却重定向到https://localhost:7027/MicrosoftIdentity/Account/Error并出现404错误。当前在Visual Studio调试模式下运行,缺乏B2C配置经验,不清楚问题出在哪里。

附原配置代码:

Program.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Add Azure AD B2C authentication
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));

builder.Services.AddAuthorization();

// Apply [Authorize] attribute globally
builder.Services.AddRazorPages(options =>
{
    options.Conventions.AuthorizePage("/");
    options.Conventions.AuthorizeFolder("/");
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();

appsettings.json

{
  "AzureAdB2C": {
    "Instance": "https://<my-tenant-name>.b2clogin.com",
    "Domain": "<my-tenant-name>.onmicrosoft.com",
    "TenantId": "<my-tenant-id>",
    "ClientId": "<my-client-id>",
    "ClientSecret": "<my-client-secret>",
    "CallbackPath": "/signin-oidc",
    "SignUpSignInPolicyId": "<my-signinsignup-policy>",
    "ResetPasswordPolicyId": "<my-passwordreset-policy>",
    "EditProfilePolicyId": "<my-profileediting-policy>"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

排查与解决方法

1. 补充Microsoft Identity UI支持

Microsoft Identity Web默认依赖内置的身份相关页面(登录、错误页等),但Razor Pages项目默认未包含这些页面,导致重定向到错误页时找不到对应路由。

修正步骤:
在认证配置中添加AddMicrosoftIdentityUI()方法,并映射控制器路由:

// 修改认证配置部分
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"))
    .AddMicrosoftIdentityUI(); // 新增此行

// 在端点映射部分新增控制器路由
app.MapRazorPages();
app.MapControllers(); // 新增此行,支持Identity UI的控制器路由

2. 清理冗余的全局授权规则

当前代码同时使用AuthorizePage("/")和AuthorizeFolder("/"),会导致重复授权规则,可能引发重定向逻辑冲突。

修正步骤:
保留AuthorizeFolder("/")即可(已覆盖所有页面),删除AuthorizePage("/"):

builder.Services.AddRazorPages(options =>
{
    // options.Conventions.AuthorizePage("/"); 移除此行
    options.Conventions.AuthorizeFolder("/");
});

3. 验证Azure B2C应用注册配置

确保Azure B2C租户中的应用注册信息与本地配置一致:

  • 回调URL(Redirect URI)设置为https://localhost:7027/signin-oidc(与appsettings.json的CallbackPath匹配)
  • 应用注册已启用"ID令牌"(OpenID Connect认证必需)
  • 客户端密钥(ClientSecret)与配置文件中的值完全一致且未过期

4. 启用调试日志定位细节

提高认证相关日志级别,查看具体错误信息:
修改appsettings.json的Logging配置:

"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore.Authentication": "Debug",
    "Microsoft.Identity.Web": "Debug",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
}

在Visual Studio输出窗口查看调试日志,定位认证过程中的具体异常。

修正后的完整Program.cs示例

using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Add Azure AD B2C authentication with Identity UI support
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"))
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization();

// Apply [Authorize] attribute globally to all pages
builder.Services.AddRazorPages(options =>
{
    options.Conventions.AuthorizeFolder("/");
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapControllers(); // 添加Identity UI所需的控制器路由

app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:10:57