如何使用Azure AD獲取應用程序令牌以查詢具有應用程序憑據(=無用戶模擬)的SharePoint?使用Azure AD令牌應用程序訪問SharePoint Online
下面的代碼完全適用於查詢數據的用戶,但我們需要不帶模擬像列出集合中的所有網站,不考慮用戶權限等
拋出異常獲取信息:
的 「Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException」 發生在mscorlib.dll中,但未在用戶代碼中處理
附加信息:AADS TS70001:與標識符 'XXX' 應用目錄sharepoint.com未找到
代碼來獲得令牌:
internal static async Task<string> GetSharePointAccessToken(string url, string userAccessTokenForImpersonation)
{
string clientID = @"<not posted on stack overflow>";
string clientSecret = @"<not posted on stack overflow>";
var appCred = new ClientCredential(clientID, clientSecret);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");
// Use user assetion if provided, otherwise use principal account
AuthenticationResult authResult = null;
if (string.IsNullOrEmpty(userAccessTokenForImpersonation))
{
authResult = await authContext.AcquireTokenAsync(new Uri(url).GetLeftPart(UriPartial.Authority), appCred);
}
else
{
authResult = await authContext.AcquireTokenAsync(new Uri(url).GetLeftPart(UriPartial.Authority), appCred, new UserAssertion(userAccessTokenForImpersonation));
}
return authResult.AccessToken;
}
測試代碼:
// Auth token from Bearer https://xxx.azurewebsites.net/.auth/me
string authHeader = @"<valid jwt bearer token from azure auth>";
var sharePointUrl = @"https://xxx.sharepoint.com/sites/testsite/";
string sharePrincipalToken = await GetSharePointAccessToken(sharePointUrl, null); // <-- doesn't work
string sharePointUserToken = await GetSharePointAccessToken(sharePointUrl, authHeader); // <-- works
Azure AD權限: