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

如何在Blazor WebAssembly中借助Azure ADB2C MSAL实现单点登录

Blazor WebAssembly Azure AD B2C 静默单点登录实现方案

核心逻辑:默认Blazor WASM MSAL模板仅在访问带[Authorize]标记的受保护页面时才会触发认证校验,要实现全应用范围的自动静默登录,只需要在应用初始化阶段主动调用MSAL提供的静默登录接口,无需用户交互即可读取现有AD B2C会话完成认证。

前置配置调整

首先确认Program.cs中MSAL服务注册的配置符合静默登录要求:

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    // 缓存位置设置为localStorage,确保可以读取跨应用、跨标签页的登录会话
    options.ProviderOptions.Cache.CacheLocation = "localStorage";
    options.ProviderOptions.LoginMode = "redirect";
});

实现静默登录触发逻辑

可根据业务场景选择以下任意一种实现方式:

方式1:App.razor组件初始化时触发

适合大多数场景,静默认证和组件初始化并行执行,不影响公开页面加载速度:

@inject AuthenticationStateProvider AuthStateProvider
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Microsoft.Identity.Client

<Router AppAssembly="@typeof(App).Assembly">
    <!-- 原有Router配置保持不变 -->
</Router>

@code {
    protected override async Task OnInitializedAsync()
    {
        try
        {
            // 主动调用静默登录接口,存在有效会话时自动完成认证
            await ((RemoteAuthenticationService<RemoteAuthenticationState, RemoteUserAccount, MsalProviderOptions>)AuthStateProvider)
                .SignInSilent();
        }
        catch (MsalUiRequiredException)
        {
            // 无有效登录会话,需用户主动触发登录,此处无需额外处理
        }
    }
}

方式2:应用启动前全局触发

适合需要在所有页面加载前完成身份状态校验的场景:

  1. 首先创建认证初始化服务:
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.Identity.Client;

public class AuthInitializationService
{
    private readonly IAuthenticationService _authService;

    public AuthInitializationService(IAuthenticationService authService)
    {
        _authService = authService;
    }

    public async Task InitializeSilentAuthAsync()
    {
        try
        {
            await _authService.SignInSilent();
        }
        catch (MsalUiRequiredException)
        {
            // 无有效会话,不做处理
        }
    }
}
  1. 在Program.cs中注册服务并在应用启动前执行初始化:
builder.Services.AddScoped<AuthInitializationService>();

var host = builder.Build();

// 执行静默认证初始化
var authInitService = host.Services.GetRequiredService<AuthInitializationService>();
await authInitService.InitializeSilentAuthAsync();

await host.RunAsync();

校验配置

确保Azure AD B2C侧的用户流SSO配置为跨应用生效,同时应用注册的重定向URI、注销重定向URI配置正确,否则静默登录会抛出非MsalUiRequiredException类型的异常,需根据异常信息排查配置问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:27:02