使用Sharepoint Python API和客户端凭证访问MS365文件

0 投票
2 回答
20 浏览
提问于 2025-04-14 16:14

我正在尝试通过Sharepoint的Python API读取存储在OneDrive中的Excel文件内容。我看到了一些关于使用用户名和密码进行身份验证的例子,但没有看到使用应用程序凭据(client_id/client_secret)的方法。

(1) 我在Sharepoint网站上创建了凭据,链接是:
https://MYDOMAIN.sharepoint.com/sites/engineering/_layouts/15/appregnew.aspx

(2) 我通过以下链接给这些凭据授予了权限:
https://MYDOMAIN-admin.sharepoint.com/_layouts/15/appinv.aspx

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
</AppPermissionRequests>

(3) 然后我尝试了以下代码片段:

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.client_context import ClientCredential

# sharepoint app: https://outlyer.sharepoint.com/sites/engineering/_layouts/15/appregnew.aspx
client_id = "..."
client_secret = "..."
site_url = "https://MYDOMAIN.sharepoint.com/"


client_credentials = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(client_credentials)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))

但是这返回了一个身份验证错误:

requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://MYDOMAIN.sharepoint.com/_api/Web

有没有什么想法?微软的文档对我来说实在是太复杂了,尤其是因为似乎有很多不同的范围/方法可以处理应用程序权限。

2 个回答

0

谢谢你,RaytheonXie-MSFT,给我的建议。我之前对shareplum这个库不太熟悉。不过,我用下面的代码片段成功运行了它,但我还是想搞清楚msal库到底出了什么问题?

# connect to MS365 Graph API (get access token headers), while
# disabling SSL cert verification & suppressing resulting warning

with warnings.catch_warnings():
    warnings.simplefilter("ignore")

    application = ConfidentialClientApplication(
        client_id=CONF["azure"]["client_id"],
        client_credential=CONF["azure"]["client_secret"],
        authority=f"https://login.microsoftonline.com/{CONF['azure']['tenant_id']}",
        verify=False,
    )

    SCOPE = "https://graph.microsoft.com/.default"
    result = application.acquire_token_for_client(scopes=[SCOPE])
    access_token = result["access_token"]

    headers = {
        "Authorization": "Bearer " + access_token,
        "Accept": "application/json",
        "Content-Type": "application/json",
    }

# Because of the SSL issue, we cannot use the MS Graph SDK for queries
# Construct direct URL API queries instead, and secure with certifi
# https://urllib3.readthedocs.io/en/1.26.x/user-guide.html#ssl
# use http.request() to make API calls

http = urllib3.PoolManager(cert_reqs="CERT_REQUIRED", ca_certs=certifi.where())
0

你可以参考下面的代码来访问MS365文件。

from shareplum import Site
from shareplum.site import Version

# SharePoint site URL
site_url = "https://yourdomain.sharepoint.com/sites/yoursite/"

# Client ID and Secret for the Azure App Registration
client_id = "your_client_id"
client_secret = "your_client_secret"

# SharePoint library name
library_name = "Documents"

# Initialize the Site object
site = Site(site_url, version=Version.v365, auth="client_credentials", client_id=client_id, client_secret=client_secret)

# Get the library
sp_library = site.List(library_name)

# Print all files in the library
for row in sp_library.get_list_items():
    print(row["FileLeafRef"])

撰写回答