.NET 8 Minimal API创建GraphServiceClient查询组名遇配置权限问题
我正在用C#/.NET 8开发供Web-GUI调用的Minimal API,API会接收包含组ID列表的JWTSecurityToken,需要调用Microsoft Graph查询这些组的名称。
在Entra管理中心,我的应用已完成配置,且管理员已授予Group.Read.All API权限,同时JWTSecurityToken的payload中scp字段包含该权限。
当前实现与错误情况
我尝试通过以下代码创建GraphServiceClient:
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(clientSecretCredential, scopes); // tenantId、clientId、clientSecret和scopes从appsettings.json或secrets.json读取。
随后尝试获取组名称:
string groupId = "<测试用硬编码的令牌中存在的组ID>"; var singleGroup = await graphClient.Groups[groupId].GetAsync(); Console.WriteLine(singleGroup.DisplayName);
根据scopes的不同取值,会出现不同错误:
情况1:scopes为以下值时
scopes = ["Group.Read.All"]; scopes = [$"api://{clientId}/Group.Read.All"];
报错信息:
Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed:
AADSTS1002012: 提供的scope值无效。
客户端凭据流必须使用以/.default结尾的资源标识符(应用ID URI)作为scope值。
情况2:scopes为包含.default的变体时
scopes = ["Group.Read.All", "https://graph.microsoft.com/.default"]; scopes = ["Group.Read.All", "graph.microsoft.com/.default"]; scopes = ["Group.Read.All", ".default"]; scopes = ["graph.microsoft.com/.default"];
报错信息:
Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed:
AADSTS70011: 请求必须包含'scope'输入参数。提供的scope输入参数值无效。
该scope无效。
情况3:scopes为以下值时
scopes = [".default"]; scopes = ["https://graph.microsoft.com/.default"];
报错信息:
Microsoft.Graph.Models.ODataErrors.ODataError: 权限不足,无法完成操作。
疑问与问题
我是否使用了正确的Graph包?示例中出现
Microsoft.Graph或Microsoft.Identity.Web.MicrosoftGraph,哪个才是正确的选择?我的启动配置是否正确?当前代码如下:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() .AddInMemoryTokenCaches();
多数示例使用:
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
我后续尝试添加以下代码时出现编译错误:
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
请求
请提供适用于.NET 8的可用示例,我找到的示例多为旧版Graph,与.NET 8不兼容。
补充:API权限配置截图显示已添加Group.Read.All应用权限,状态为已授予。
内容的提问来源于stack exchange,提问作者Martin

