我正在从 ADAL 迁移到 MSAL 并收到无效范围错误

I am migrating from ADAL to MSAL and getting invalid scope error

在我的代码中,我正在从使用 Microsoft.IdentityModel.Clients.ActiveDirectory 切换到使用 Microsoft.Identity.Client 。

以前的实现:

var authContext = new AuthenticationContext(String.Format(Authority));
var credential = new ClientCredential(IssuingResource, Secret);
private static AuthenticationResult authResult = await authContext.AcquireTokenAsync(appSettings.URI, credential);
return authResult.AccessToken;

当前实施:

string[] scopes = { appSettings.URI + "/.default" };
var cca = ConfidentialClientApplicationBuilder.Create(IssuingResource).WithClientSecret(Secret).WithAuthority(Authority).Build();
private static AuthenticationResult authResult = await cca.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;

当前的实现抛出异常: AADSTS70011:提供的请求必须包含 'scope' 输入参数。为输入参数 'scope' 提供的值无效。

我是不是漏掉了什么? 任何人都可以指导我吗? 提前致谢。

对于 client credentials flows,范围始终为 "resource/.default" 形状,因为应用程序权限需要静态设置(在门户中或通过 PowerShell),然后由租户管理员授予。

例如:

Microsoft Graph: https://graph.microsoft.com/.default

Microsoft 365 Mail API: https://outlook.office.com/.default

Azure Key Vault: https://vault.azure.net/.default

这是使用机密客户端应用程序获取访问令牌的代码:

public string GetAccessToken()
{

       var tenantId = "";
       var clientId = "";    
       var authorityUri = $"https://login.microsoftonline.com/{tenantId}";    
       var redirectUri = "http://localhost:4030";   
       var scopes = new List<string> { "https://graph.microsoft.com/.default" };    
       var clientSecret = "";
         
       var confidentialClient = ConfidentialClientApplicationBuilder    
              .Create(clientId)    
              .WithClientSecret(clientSecret)
              .WithAuthority(new Uri(authorityUri))
              .Build();

       var accessTokenRequest = confidentialClient.AcquireTokenForClient(scopes);

       var accessToken = accessTokenRequest.ExecuteAsync().Result.AccessToken; 

       return accessToken;    
}