克服使用 REST API 与 SharePoint Online 交互时的身份验证错误

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

现在,在更新为通过证书进行身份验证后,我从下面的函数尝试列出共享点文件夹中的文件时得到的错误是:

An error occurred: AuthenticationContext.acquire_token_for_app() got an unexpected keyword argument 'client_credential'

按如下方式调用时:

list_files_in_sharepoint_with_cert(
    '123456789',
    '987654321', 
    'c:\\users\\qqq\\xxx.pfx',
    'https://xxx.sharepoint.com',
    '/sites/yyy/Shared Documents/')

代码已更新为使用证书,但我认为我使用证书进行身份验证的方式有问题。

还更正了 Azure 应用程序权限,如下所示:

这是该函数的代码。

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.auth.token_response import TokenResponse
from office365.sharepoint.client_context import ClientContext


def list_files_in_sharepoint_with_cert(tenant_id, client_id, certificate_path, sharepoint_site_url, sharepoint_folder_url):
    """
    Lists files in a specified SharePoint folder or entire site using certificate-based authentication.

    :param tenant_id: Azure AD Tenant ID.
    :param client_id: The Azure AD application (client) ID.
    :param certificate_path: Path to the .pfx or .cer certificate file.
    :param sharepoint_site_url: The URL of the SharePoint site.
    :param sharepoint_folder_url: The optional URL of the SharePoint folder.
    """
    try:
        # Authenticate
        authority_url = f'https://login.microsoftonline.com/{tenant_id}'
        auth_ctx = AuthenticationContext(authority_url)
        client_credential = ClientCredential(client_id, certificate_path)
        
        breakpoint()
        auth_ctx.acquire_token_for_app(client_credential=client_credential)

        ctx = ClientContext(sharepoint_site_url, auth_ctx)

        # Rest of the function remains the same as before...

    except Exception as e:
        print(f"An error occurred: {e}")


python azure sharepoint
1个回答
1
投票

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

即,您的应用程序注册中有“Sites.FullControl.All”行,并要求“所有范围”(事实上,您没有指定任何范围,默认情况下要求所有范围)。并且您的代码正在使用“客户端密钥”(这比证书弱)。

你可以(应该可以):

  • 删除“Sites.FullControl.All”(应用程序范围)。要读/写文件或文件夹,您无论如何都不需要它。
  • 使用证书作为“秘密”而不是击键(即代替“客户端秘密”)
  • 连接时明确指定范围,不包括应用程序级别范围。
© www.soinside.com 2019 - 2024. All rights reserved.