如何使用MSAL获取Sharepoint API的访问令牌

问题描述

我有.NET Core控制台应用程序,我正在尝试使用MSAL.NET库获取SharePoint API的访问令牌。

在Azure中,我为我的应用程序定义了一个新权限。

enter image description here

代码中,我正在获取acces令牌

var clientApp = PublicclientApplicationBuilder.Create("<client_id>")
                .WithAuthority($"https://login.microsoftonline.com/{<tenant_id>}")
                .WithDefaultRedirectUri()
                .Build();
var accounts = await clientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
var authResult = await clientApp.AcquiretokenSilent("https://tenant.sharepoint.com/.default",firstAccount).ExecuteAsync();

AcquiretokenSilent抛出MsalUirequiredException,所以我打电话

authResult = await clientApp.AcquiretokenByUsernamePassword(new string[] { "https://tenant.sharepoint.com/.default" },"userName",<password>).ExecuteAsync();

但返回

远程服务器返回错误:(401)未经授权。

根据MSAL,可以使用用户的凭据来获取访问令牌。

如果我基于v2-oauth-ropc发送简单的POST请求,则会收到访问令牌。 我想MSAL.NET在内部发送相同的POST请求。

解决方法

代码应该起作用。请提供请求或相关ID和时间戳。