使用 REST API 与 SharePoint Online 交互时克服 403 错误

问题描述 投票:0回答:1

下面的函数尝试列出共享点文件夹中的文件,不断返回错误(xxx 是域):

An error occurred: (None, None, "403 Client Error: Forbidden for url: https://xxx.sharepoint.com/_api/Web/getFolderByServerRelativeUrl('%2Fsites%2FBRB%2FShared%20Documents')")

按如下方式调用时:

sharepoint_site_url = 'https://xxx.sharepoint.com'
sharepoint_folder_url = '/sites/BRB/Shared Documents'
  
list_files_in_sharepoint(spo_client_id, spo_secret, sharepoint_site_url, sharepoint_folder_url)

因此身份验证有效(或者我会看到不同的错误),但在尝试访问共享点站点时失败。

我认为这可能是Azure中应用程序的设置,所以如下所示。有什么遗漏或错误吗?

这是该函数的代码。

def list_files_in_sharepoint(client_id, client_secret, sharepoint_site_url, sharepoint_folder_url=None):
    """
    Lists files in a specified SharePoint folder or entire site if no folder is specified.

    :param client_id: The client ID for SharePoint authentication.
    :param client_secret: The client secret for SharePoint authentication.
    :param sharepoint_site_url: The URL of the SharePoint site.
    :param sharepoint_folder_url: The optional URL of the SharePoint folder.
    """
    try:
        # Authenticate
        auth_ctx = AuthenticationContext(sharepoint_site_url)
        if not auth_ctx.acquire_token_for_app(client_id=client_id, client_secret=client_secret):
            print("Authentication failed")
            return
        ctx = ClientContext(sharepoint_site_url, auth_ctx)
        breakpoint()
        if sharepoint_folder_url:
            # Get the folder and load files
            folder = ctx.web.get_folder_by_server_relative_url(sharepoint_folder_url)
            ctx.load(folder)
            ctx.load(folder.files)
            ctx.execute_query()

            files = folder.files
            if len(files) == 0:
                print(f"No files found in folder '{sharepoint_folder_url}'")
            else:
                print(f"Files in folder '{sharepoint_folder_url}':")
                for file in files:
                    print(f"- {file.properties['Name']}")
        else:
            # List files in the entire site
            files = ctx.web.lists.get_by_title("Documents").root_folder.files
            ctx.load(files)
            ctx.execute_query()

            if len(files) == 0:
                print("No files found in the site")
            else:
                print("Files in the site:")
                for file in files:
                    print(f"- {file.properties['Name']}")

    except Exception as e:
        print(f"An error occurred: {e}")
python azure sharepoint
1个回答
0
投票

是的,应用程序权限仅支持证书身份验证。您混合了“委托”和“应用程序”:

您的应用程序中有“Sites.FullControl”,并要求“所有范围”(事实上,您没有指定任何范围,这要求使用“.default”范围来指定所有范围)。

您的代码正在使用“客户端密钥”(这比证书弱)。

你可以(应该可以):

  • 删除“Sites.FullControl”(应用程序范围)。
  • 使用证书作为秘密而不是击键(即代替“客户端秘密”)
  • 连接时明确指定范围,不包括应用程序级别范围。
© www.soinside.com 2019 - 2024. All rights reserved.