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

在Blazor WASM应用中调用Graph API时强制触发Azure MFA

在Blazor WASM中强制用户完成Azure MFA以满足Graph API的条件访问要求

第一步:修复身份验证上下文与条件访问策略的关联

报错提示The configured Conditional Access authentication context c1 is not found in any of Conditional Access policies,说明你配置的身份验证上下文(AC)c1未绑定到对应的条件访问(CA)策略,需先完成基础配置:

  • 在Azure AD的「身份验证方法」>「身份验证上下文」中,确认c1已创建
  • 编辑要求MFA的CA策略,在「云应用或操作」>「用户操作」里选择「身份验证上下文」并指定c1;同时在「授予」环节勾选「需要多重身份验证」

第二步:在Blazor WASM中请求带身份验证上下文的令牌

Blazor WASM依赖MSAL.NET处理身份验证,需在请求令牌时指定身份验证上下文,确保令牌包含MFA验证信息。

方案1:登录时强制MFA验证

修改Program.cs中的MSAL配置,在登录请求中添加身份验证上下文参数:

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/.default");
    
    // 指定身份验证上下文c1
    options.ProviderOptions.AdditionalAuthenticationParameters.Add(
        "authentication_context_class_reference", "c1");
});

方案2:按需触发MFA(仅针对PIM激活操作)

如果仅需在调用PIM激活接口时触发MFA,可在获取令牌时动态指定身份验证上下文:

@inject IAccessTokenProvider TokenProvider
@inject NavigationManager NavigationManager

private async Task ActivatePimAssignment()
{
    var tokenRequest = new AccessTokenRequestOptions
    {
        Scopes = new[] { "https://graph.microsoft.com/.default" },
        AdditionalAuthenticationParameters = new Dictionary<string, string>
        {
            { "authentication_context_class_reference", "c1" }
        }
    };

    var result = await TokenProvider.RequestAccessToken(tokenRequest);
    if (result.TryGetToken(out var token))
    {
        // 将令牌传递给后端,由后端调用Graph API
        await BackendApiClient.SendPimActivationRequest(token.Value);
    }
    else
    {
        // 引导用户完成MFA验证
        NavigationManager.NavigateTo(result.RedirectUrl);
    }
}

第三步:捕获Graph API错误并触发重新验证

若调用Graph API仍返回MFA错误,需在后端捕获异常并向前端传递验证信号:

try
{
    await graphClient.IdentityGovernance.PrivilegedAccess.Group.AssignmentScheduleRequests.PostAsync(privilegedAccessGroupAssignmentScheduleRequest);
}
catch (ServiceException ex) when (ex.Message.Contains("Additional verification (Azure MFA) required"))
{
    throw new HttpRequestException("需完成多重身份验证才能继续", null, HttpStatusCode.Unauthorized);
}

前端收到该错误后,触发重新登录流程,强制用户完成MFA验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:06:05