You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharePoint API调用返回401,但浏览器查询正常求助

SharePoint API 调用返回401未授权问题排查与修复

核心原因

浏览器访问时会自动携带你的登录凭证(如会话Cookie),但jQuery AJAX默认不会发送这些凭证,导致SharePoint服务器无法识别你的身份,返回401未授权错误。

具体修复步骤

1. 开启AJAX凭证携带配置

在$.ajax配置中添加xhrFields: { withCredentials: true },强制AJAX请求携带当前会话的认证Cookie,和浏览器访问行为保持一致。这是解决问题的关键。

2. 移除不必要的请求头配置

GET请求没有请求体,contentType字段用于设置请求体的编码类型,对GET请求完全无效,建议删除该配置项,避免干扰服务器解析。

3. 检查自定义头的必要性

你添加的info1: sessionId自定义头,如果不是SharePoint服务器要求的认证字段,对身份验证没有作用(浏览器访问时未携带该头也能成功)。如果不是业务逻辑必需,可直接删除;如果是必需项,需确认sessionId的有效性。

修改后的代码示例

function sharePointAPITestCall(){
    $.ajax({
        url: "https://testWebsite.com/_api/search/query?querytext=%27test%27",
        type: "GET",
        headers: {"info1": sessionId}, // 业务非必需可删除
        dataType: "json",
        xhrFields: {
            withCredentials: true // 关键:携带认证Cookie
        },
        success: async function (response) {
            const results = response.PrimaryQueryResult.RelevantResults.Table.Rows;

            for (const result of results) {
                console.log(result.Cells)
                const extension = result.Cells.find(cell => cell.Key === 'FileExtension').Value;
                if (extension && extension.toLowerCase() !== 'aspx') {
                    const title = result.Cells.find(cell => cell.Key === 'Title').Value;
                    const url = result.Cells.find(cell => cell.Key === 'Path').Value;
                    let hitHighlightedSummary = result.Cells.find(cell => cell.Key === 'HitHighlightedSummary').Value;
                    console.log(hitHighlightedSummary)
                    try {
                        const xmlContent = await readUrlContents(url);
                        if (xmlContent) {
                            console.log(xmlContent)
                        }
                    } catch (error) {
                        console.error(error);
                    }
                }
            }
        },
        error: function (xhr, status, error) {
            if (xhr.status === 500 || xhr.status === 400) {
                alert('Data Fetch Failed. Connect with System Administrator.');
            } else {
                alert('Data Fetch Failed. Try again sometime.');
            }
        }
    });
}

额外注意事项

  • 跨域场景限制:如果你的页面域名与SharePoint站点不同,即使开启withCredentials,仍需SharePoint管理员配置CORS策略,允许你的域名携带凭证访问。无服务器权限的话,需联系管理员处理,或调整应用部署到同域环境。
  • 浏览器Cookie限制:部分浏览器默认禁用第三方Cookie,跨域场景下会导致凭证无法发送。这种情况需要用户调整浏览器Cookie设置,或由管理员配置SharePoint的CORS策略适配。

内容的提问来源于stack exchange,提问作者J3D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:20:27