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

Blazor 8 Web App集成Azure B2C:求完整配置指南及参考示例

Blazor Web App(混合托管)集成Azure B2C指南及参考配置

一、核心配置步骤(从无授权模板开始)

  • 安装依赖包:在项目中安装Microsoft.AspNetCore.Authentication.OpenIdConnect和Microsoft.Identity.Web NuGet包
  • 配置appsettings.json:添加Azure B2C相关参数,示例如下:
    "AzureAdB2C": {
      "Instance": "https://你的租户域名.b2clogin.com/",
      "Domain": "你的租户域名.onmicrosoft.com",
      "ClientId": "你的应用客户端ID",
      "SignedOutCallbackPath": "/signout/B2C_1_你的注册登录策略名",
      "SignUpSignInPolicyId": "B2C_1_你的注册登录策略名"
    }
    
  • 配置Program.cs:添加身份验证服务、启用授权中间件,保护Blazor路由
  • 组件授权配置:在App.razor中添加<CascadingAuthenticationState>和<AuthorizeRouteView>,对需要授权的页面做访问控制

二、Program.cs核心配置示例

var builder = WebApplication.CreateBuilder(args);

// 添加身份验证服务
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

// 添加MVC与Blazor相关服务
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();

var app = builder.Build();

// 配置请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

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

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

// 映射路由端点
app.MapRazorPages();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

三、自定义声明映射处理

如果需要解析自定义策略中的自定义声明,可在OpenID Connect配置中添加声明转换逻辑:

.AddMicrosoftIdentityWebApp(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options);
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = context =>
        {
            // 示例:映射自定义声明extension_CustomClaim到本地声明CustomClaim
            var customClaim = context.Principal.FindFirst("extension_CustomClaim");
            if (customClaim != null)
            {
                context.Principal.Identities.First().AddClaim(new Claim("CustomClaim", customClaim.Value));
            }
            return Task.CompletedTask;
        }
    };
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:32:48