SharePoint CSOM使用Client ID与密钥调用ExecuteQuery时遭遇401 Unauthorized错误的求助
我现在碰到个棘手的问题:用Client ID和密钥连接SharePoint站点时,调用ExecuteQuery()方法一直返回401 Unauthorized错误,但换成Client ID加证书的方式就能正常运行,完全搞不懂哪里出问题了。
先说说我已经做过的配置:
- 应用注册时,给了Microsoft Graph和SharePoint API的全站点控制权限
- 已经通过
appinv.aspx页面完成了应用的信任配置 - 知道ACS要退役了,所以特意用的Azure AD OAuth方式(代码里用MSAL获取令牌)
下面是我的测试代码,证书认证的部分能正常打印站点标题、读取列表集合,但密钥认证的部分一走到ExecuteQuery()就直接报错:
static void Main(string[] args) { var authManager = new AuthenticationManager("***************************", "C:\\Program Files\\OpenSSL-Win64\\bin\\certificate.pfx", "*******", "********.onmicrosoft.com"); using (var cc = authManager.GetContext("https://****.sharepoint.com/sites/****")) { cc.Load(cc.Web, p => p.Title); cc.ExecuteQuery(); Console.WriteLine(cc.Web.Title); ListCollection listCollection = cc.Web.Lists; cc.ExecuteQuery(); // 这里完全正常 } ; // 替换为你的SharePoint Online信息 string siteUrl = "****************************"; string tenantId = "***************************"; string clientId = "********************************"; string clientSecret = "******************************"; // 应用密钥 try { using (var context = GetClientContextWithOAuth(siteUrl, tenantId, clientId, clientSecret)) { // 示例:获取网站标题 Web web = context.Web; context.Load(web, w => w.Title); context.ExecuteQuery(); // 这里抛出401 Unauthorized错误 Console.WriteLine("Connected to: " + web.Title); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } private static ClientContext GetClientContextWithOAuth(string siteUrl, string tenantId, string clientId, string clientSecret) { // Azure AD OAuth 2.0端点 string authority = $"https://login.microsoftonline.com/*******************"; // 使用MSAL获取访问令牌 var app = ConfidentialClientApplicationBuilder.Create(clientId) .WithClientSecret(clientSecret) .WithAuthority(new Uri(authority)) .Build(); var authResult = app.AcquireTokenForClient(new[] { $"{siteUrl}/.default" }).ExecuteAsync().Result; if (authResult == null) { throw new Exception("Failed to acquire the access token."); } // 使用访问令牌认证ClientContext var context = new ClientContext(siteUrl); context.ExecutingWebRequest += (sender, e) => { e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + authResult.AccessToken; }; return context; }
有没有大佬能指点下?ACS退役后,用Client ID+密钥访问SharePoint站点是不是还有什么特殊的权限配置或者遗漏的步骤?
备注:内容来源于stack exchange,提问作者Dhanusha
相关产品推荐
相关产品推荐

