调用SharePoint端点出现401(Unauthorized)错误,此前为CORS问题求助
调用SharePoint端点时出现401未授权错误,此前为解决CORS错误(提示来自'http://127.0.0.1:1234'的XMLHttpRequest请求因缺少Access-Control-Allow-Origin头被拦截),在HTTP响应头中添加了Access-Control-Allow-Origin: *,之后就出现了401错误。请求响应示例:GET http://www.test.com/Shared%20Documents/query%20result%20BEFORE.xml 401 (Unauthorized)
相关代码:
function testCall2() { const xhr1 = new XMLHttpRequest(); const URL= "http://test.com/_api/search/query?querytext=%27BEFORE%27" xhr1.open("GET", URL); xhr1.onreadystatechange = function() { if (xhr1.readyState === 4) { if (xhr1.status === 200) { const response = xhr1.responseText; // Process the response as needed console.log(`XHR1 Success!! ${response}`); } else { console.error('XHR1 Error:', xhr1.statusText); } } }; xhr1.send(); }
修正CORS头配置,禁用通配符
*
SharePoint依赖Cookie/NTLM/Kerberos等带凭证的认证方式,而浏览器规定:当请求携带凭证时,Access-Control-Allow-Origin不能设为*,必须指定具体的源(比如http://127.0.0.1:1234),同时要添加Access-Control-Allow-Credentials: true头。在请求中开启凭证携带
修改你的XHR代码,添加xhr1.withCredentials = true;,否则浏览器不会自动携带认证所需的Cookie,导致SharePoint返回401。修改后的代码片段:xhr1.open("GET", URL); xhr1.withCredentials = true; // 新增这一行 xhr1.onreadystatechange = function() { // ... 原有逻辑 };确认CORS配置的生效层级
SharePoint和IIS都能配置CORS,要避免冲突:- 如果是SharePoint Server,优先通过站点根目录的Web.config配置CORS,而非直接在IIS管理器中设置;
- 配置示例(Web.config中添加):
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://127.0.0.1:1234" /> <add name="Access-Control-Allow-Credentials" value="true" /> <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" /> <add name="Access-Control-Allow-Headers" value="Content-Type,Accept" /> </customHeaders> </httpProtocol> </system.webServer>
检查OPTIONS预请求的处理
跨域GET请求如果带凭证,浏览器会先发送OPTIONS预请求,要确保IIS/SharePoint允许OPTIONS请求匿名访问,否则预请求会先返回401,导致主请求失败。可以在IIS中为OPTIONS方法设置匿名授权,或者在Web.config中添加:<system.web> <authorization> <allow verbs="OPTIONS" users="*" /> <deny users="?" /> </authorization> </system.web>验证用户权限
确认当前浏览器登录的用户对目标SharePoint站点、文档库以及搜索API有读取权限,可以直接在浏览器中访问http://test.com/_api/search/query?querytext=%27BEFORE%27,看是否能正常返回结果,排除权限本身的问题。
内容的提问来源于stack exchange,提问作者J3D

