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

如何在.NET 8 Blazor Web App中配置Azure AD B2C?求可行示例

.NET 8 Blazor 项目配置 Azure AD B2C 示例

Blazor Server 项目配置步骤

1. 安装依赖包

执行以下命令安装必要的NuGet包:

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

2. 配置 appsettings.json

添加Azure AD B2C的核心配置项:

"AzureAdB2C": {
  "Instance": "https://你的租户名称.b2clogin.com/",
  "Domain": "你的租户名称.onmicrosoft.com",
  "TenantId": "你的租户GUID",
  "ClientId": "你的应用客户端ID",
  "ClientSecret": "你的应用客户端密钥",
  "CallbackPath": "/signin-oidc",
  "SignUpSignInPolicyId": "B2C_1_signup_signin",
  "ResetPasswordPolicyId": "B2C_1_reset_password",
  "EditProfilePolicyId": "B2C_1_edit_profile"
}

3. 配置 Program.cs

注入认证服务并启用身份验证中间件:

// 添加Azure AD B2C认证服务
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));

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

// 添加Blazor Server身份验证支持
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();

// ...

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

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

4. 在页面中添加登录/登出入口

修改 _Host.cshtml,添加身份状态相关的操作入口:

<component type="typeof(App)" render-mode="ServerPrerendered" />

@if (User.Identity?.IsAuthenticated ?? false)
{
    <a asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">登出</a>
}
else
{
    <a asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">登录</a>
}

Blazor WebAssembly (WSAM) 项目配置步骤

1. 安装依赖包

执行以下命令安装认证相关包:

dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Authentication

2. 配置 appsettings.json

添加Azure AD B2C配置:

"AzureAdB2C": {
  "Authority": "https://你的租户名称.b2clogin.com/你的租户名称.onmicrosoft.com/B2C_1_signup_signin",
  "ClientId": "你的应用客户端ID",
  "ValidateAuthority": false
}

3. 配置 Program.cs

注入MSAL认证服务:

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    // 若需要调用API,添加对应的权限范围
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://你的租户名称.onmicrosoft.com/api/你的API权限范围");
});

await builder.Build().RunAsync();

4. 配置 App.razor

添加身份验证状态管理与路由授权:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    @if (!context.User.Identity?.IsAuthenticated ?? true)
                    {
                        <RedirectToLogin />
                    }
                    else
                    {
                        <p>你没有权限访问此页面。</p>
                    }
                </NotAuthorized>
            </AuthorizeRouteView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>页面未找到</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>抱歉,无法找到你请求的页面。</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

5. 创建登录状态显示组件

新建 LoginDisplay.razor 文件:

<AuthorizeView>
    <Authorized>
        你好,@context.User.Identity?.Name!
        <button class="nav-link btn btn-link" @onclick="BeginLogout">登出</button>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/login">登录</a>
    </NotAuthorized>
</AuthorizeView>

@code {
    [Inject]
    public NavigationManager NavigationManager { get; set; } = default!;

    [Inject]
    public IAuthenticationService AuthenticationService { get; set; } = default!;

    private async Task BeginLogout()
    {
        await AuthenticationService.SignOutAsync();
        NavigationManager.NavigateTo("authentication/logout");
    }
}

关键配置注意事项

  • Azure AD B2C应用注册:
    • Blazor Server需注册为机密客户端,生成并保存客户端密钥,重定向URI设置为https://localhost:端口号/signin-oidc(本地开发)
    • Blazor WebAssembly需注册为公共客户端,重定向URI设置为https://localhost:端口号/authentication/login-callback(本地开发)
  • 所有配置中的占位符(如租户名称、客户端ID等)需替换为Azure B2C控制台中的实际值
  • 用户流/自定义策略ID必须与Azure B2C中创建的完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:35:14