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

ASP.NET Core 8 Blazor United项目如何配置Azure B2C身份验证?

.NET 8 Blazor United 配置Azure B2C身份验证步骤

1. 安装必要的NuGet包

在项目根目录执行以下命令:

dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI

2. 配置appsettings.json

添加Azure B2C身份验证配置项,替换为你的实际信息:

"AzureAdB2C": {
  "Instance": "https://your-b2c-domain.b2clogin.com/",
  "Domain": "your-b2c-domain.onmicrosoft.com",
  "TenantId": "your-tenant-id",
  "ClientId": "your-client-id",
  "ClientSecret": "your-client-secret", // 机密客户端场景需要,公开客户端可省略
  "SignUpSignInPolicyId": "B2C_1_SignUpSignIn", // 替换为你的B2C用户流策略ID
  "CallbackPath": "/signin-oidc",
  "SignedOutCallbackPath": "/signout-callback-oidc"
}

3. 配置Program.cs

更新服务注册和中间件配置,适配Blazor United的混合渲染模式:

var builder = WebApplication.CreateBuilder(args);

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

// 配置授权策略
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

// 添加Blazor组件服务,支持混合渲染模式
builder.Services.AddRazorComponents()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddMicrosoftIdentityConsentHandler(); // 处理权限同意流程

var app = builder.Build();

// 启用静态文件服务
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

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

// 启用身份验证和授权中间件
app.UseAuthentication();
app.UseAuthorization();

// 映射Blazor组件路由
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(Client._Imports).Assembly);

app.Run();

4. 在Blazor组件中使用身份验证

在布局组件(如MainLayout.razor)中添加登录/退出逻辑和授权视图:

<div class="main">
    <div class="top-row px-4">
        <AuthorizeView>
            <Authorized>
                <span>欢迎, @context.User.Identity.Name!</span>
                <button class="btn btn-link" @onclick="Logout">退出登录</button>
            </Authorized>
            <NotAuthorized>
                <button class="btn btn-link" @onclick="Login">登录</button>
            </NotAuthorized>
        </AuthorizeView>
    </div>

    <div class="content px-4">
        @Body
    </div>
</div>

@code {
    [Inject]
    private NavigationManager NavManager { get; set; }

    private void Login()
    {
        NavManager.NavigateTo("/MicrosoftIdentity/Account/SignIn");
    }

    private void Logout()
    {
        NavManager.NavigateTo("/MicrosoftIdentity/Account/SignOut");
    }
}

关键注意事项

  • Azure B2C应用注册配置:确保在Azure门户的应用注册中,将重定向URI设置为https://<your-domain>/signin-oidc(本地开发通常为https://localhost:5001/signin-oidc),注销URI设置为https://<your-domain>/signout-callback-oidc。
  • 混合渲染适配:ASP.NET Core 7 Blazor Server的配置未考虑WebAssembly渲染模式,因此需要添加AddInteractiveWebAssemblyRenderMode和AddMicrosoftIdentityConsentHandler来支持Blazor United的混合场景。
  • 权限配置:根据业务需求,在Azure B2C应用注册中添加必要的API权限,并确保用户同意这些权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 07:43:52