通过python从共享点检索文件时出错

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

我在尝试通过 python 从共享点下载文件时运行此脚本时遇到错误。 错误来了: 从 XML 响应检索令牌时发生错误:AADSTS53003:访问已被条件访问策略阻止。访问策略不允许令牌发行。 谁能帮我怎么做? 这是我的代码:

import shutil
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
 
sharepoint_url = "Sharepoint_site_url"
site_url = "site url"
username = "My_username"
password = "Password"
 
# File path components
library_name = "Shared Documents"
folder_name = "ABCD"
 
# Construct the full file path
file_path = f"https://xyz.sharepoint.com/sites/site_name/{library_name}/{folder_name}/"
 
# Encode the file path
encoded_file_path = file_path.replace(" ", "%20")  # Replace spaces with %20
print(encoded_file_path)
 
# Authenticate with SharePoint
ctx_auth = AuthenticationContext(sharepoint_url)
 
if ctx_auth.acquire_token_for_user(username, password):
    # Connect to SharePoint site
    ctx = ClientContext(site_url, ctx_auth)
    web = ctx.web
    ctx.load(web)

    # Get all files in the SharePoint folder
    files = ctx.web.get_folder_by_server_relative_path(file_path).files
    ctx.load(files)
    ctx.execute_query()
 
    # Create a folder on the C drive
    c_drive_folder1 = "C:/ENTERP/Raw"
    c_drive_folder2 = "C:/ENTERPR/Processed"
    os.makedirs(c_drive_folder1, exist_ok=True)
    os.makedirs(c_drive_folder2, exist_ok=True)
 
# Download and save each file to the C drive folder
for file in files:
        print(1)
        file_name = file.properties["Name"]
        file_url = f"{site_url}/{library_name}/{folder_name}/{file_name}"
        file_content = ctx.web.get_file_by_server_relative_path(file_url).read().execute_query()
 
        # Save the file to the C drive folder
        file_path_on_c_drive = os.path.join(c_drive_folder1, file_name)
        with open(file_path_on_c_drive, "wb") as local_file:
            local_file.write(file_content)
 
        print(f"Downloaded and saved: {file_name} to {file_path_on_c_drive}")
        print("Download process completed.")
else:
        print("Failed to authenticate with SharePoint.")```
        

        


I tried others codes too, but everytime i am getting the same error.
python azure sharepoint credentials microsoft365
1个回答
0
投票

您遇到的错误消息表明存在阻止令牌颁发的条件访问策略,从而阻止对 SharePoint 资源的访问。当为 Azure AD 租户配置的安全策略根据某些条件(例如位置、设备合规性或其他因素)限制访问时,通常会发生这种情况。

要解决此问题,您可能需要调整 Azure AD 租户中的条件访问策略以允许为您正在使用的场景颁发令牌,或者您可能需要免除与 Python 脚本关联的应用程序或服务主体从这些政策。

© www.soinside.com 2019 - 2024. All rights reserved.