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

ASP.NET Core API集成AAD B2C调用Graph API报unsupported_grant_type错误如何解决

问题原因

你遇到的报错和是否使用AddMicrosoftIdentityWebAppAuthentication没有关系,根本原因如下:

  • Azure AD B2C身份服务原生不支持OAuth 2.0的On-Behalf-Of(OBO)流,你当前配置的EnableTokenAcquisitionToCallDownstreamApi默认采用OBO流获取下游API的访问令牌,对应的grant_type为urn:ietf:params:oauth:grant-type:jwt-bearer,因此被B2C服务拒绝抛出该错误。
  • AddMicrosoftIdentityWebAppAuthentication是针对Web网页应用场景的授权码流配置,不符合你的API项目认证需求,直接替换也无法解决问题。
解决方案

你已经为B2C应用注册授予了Graph的应用权限,直接使用客户端凭证流调用Graph API即可,修改步骤如下:

  1. 修改服务注册代码
    保留原有API的B2C认证逻辑,删除原有的下游API调用相关配置,手动注入使用客户端凭证流的GraphServiceClient:
// 保留原有B2C API认证逻辑
services.AddMicrosoftIdentityWebApiAuthentication(Configuration, configSectionName: Constants.AzureAdB2C);

// 手动注入使用客户端凭证流的GraphServiceClient
services.AddSingleton<GraphServiceClient>(sp =>
{
    var config = sp.GetRequiredService<IConfiguration>();
    var tenantId = config["AzureAdB2C:TenantId"];
    var clientId = config["AzureAdB2C:ClientId"];
    var clientSecret = config["AzureAdB2C:ClientSecret"];
    
    // 应用权限固定使用/.default scope
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    return new GraphServiceClient(credential, scopes);
});

注:需要引入Azure.Identity命名空间使用ClientSecretCredential类

  1. 修改接口实现
    客户端凭证流没有用户登录上下文,无法直接调用/me端点,需要从当前API的认证声明中提取登录用户的ID,再调用Graph的用户查询接口:
[HttpGet]
[Route("me")]
public async Task<User> Me()
{
    // 从当前登录用户的Claims中提取B2C用户的Object ID
    var userId = User.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
    if (string.IsNullOrWhiteSpace(userId))
    {
        throw new UnauthorizedAccessException("无法获取当前用户标识");
    }
    return await graphServiceClient.Users[userId].Request().GetAsync();
}
  1. 确认权限配置
    检查Azure门户中B2C应用注册的Graph权限配置:
  • 授予的权限类型必须是应用权限,不是委派权限
  • 已经点击「授予管理员同意」按钮完成权限激活

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:36:02