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

时间:2020-09-24 11:45:21

标签: azure sharepoint-online 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请求。

1 个答案:

答案 0 :(得分:0)

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