该错误是因为在设备代码流(如后端服务或托管应用程序)中使用了 .default 范围,而这是不允许的。设备代码流应该使用客户端凭据流进行身份验证。
以下是一个解决方法的代码示例:
using Microsoft.Identity.Client;
using System;
using System.Threading.Tasks;
public class Program
{
private static string clientId = "YourClientId";
private static string clientSecret = "YourClientSecret";
private static string tenantId = "YourTenantId";
public static async Task Main()
{
var authority = $"https://login.microsoftonline.com/{tenantId}/v2.0";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
var scopes = new[] { "api:///access_as_user" };
var authenticationResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
Console.WriteLine($"Access token: {authenticationResult.AccessToken}");
// 使用获得的访问令牌调用 API
// ...
}
}
在上面的代码示例中,我们使用 Microsoft.Identity.Client 库创建了一个机密客户端应用程序。在创建应用程序时,我们使用了客户端凭据(客户端ID和客户端密钥)进行身份验证。
在 AcquireTokenForClient 方法中,我们指定了要访问的 API 的范围。请确保将
替换为你的 API 应用程序的应用程序 ID。
最后,我们通过调用 ExecuteAsync 方法来获取访问令牌。获得的访问令牌可以用于调用 API。
请注意,这只是一个示例,并且可能需要根据你的实际情况进行调整。请确保在使用代码示例之前,将其中的参数值替换为你自己的值。