azure 客户端错误:403通过Office365-REST-Python-Client禁止URL

nnvyjq4y  于 2023-08-07  发布在  Python
关注(0)|答案(1)|浏览(111)

我为我的组织尝试了以下示例代码(我的AD管理员在SharePoint中提供了完全访问权限:

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext

site_url = "https://myname.sharepoint.com"
client_id = "xxx-xxx-xxx-xxx-xxx"
client_secret = "xxxxxxxx"

ctx = ClientContext(site_url).with_credentials(ClientCredential(client_id, client_secret))

folder_path = 'sites/SOF'
root_folder = ctx.web.get_folder_by_server_relative_path(folder_path).expand(["Files"]).get().execute_query()
print("root_folder = ", root_folder)

for file in root_folder.files:
    print(file.name)

字符串
但我还是得到了

File "C:\Users\username\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://myname.sharepoint.com/_api/Web/getFolderByServerRelativePath(DecodedUrl='sites%2FSOF')?$expand=Files


我甚至尝试了site_url = "https://myname.sharepoint.com/sites/SOF",但它仍然返回:

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://myname.sharepoint.com/sites/SOF/_api/Web/getFolderByServerRelativePath(DecodedUrl='')?$expand=Files

更新:在我的浏览器中输入这个命令会返回包含所有数据的正确XML:

https://myname.sharepoint.com/sites/SOF/_api/Web/getFolderByServerRelativePath(DecodedUrl='Shared%20Documents')?$expand=Files
那么我还需要从我的管理员那里获得哪些权限呢?我的client_id和client_secret是正确的。

envsm3lx

envsm3lx1#

我创建了一个Azure AD应用


的数据
现在,当我尝试代码时,我得到了相同的错误如下:


**403 error**通常在应用程序没有足够的权限执行操作时发生。
**若要解决此错误,**请确保设置一个具有租户权限的仅应用主体,如下所示:

  • 如果您是租户管理员,则使用此https://xxx.sharepoint.com/_layouts/15/appinv.aspx
  • 如果您有全局管理员角色,则使用此https://xxx-admin.sharepoint.com/_layouts/15/appinv.aspx

我使用**https://xxx-admin.sharepoint.com/_layouts/15/appinv.aspx**授予权限:

  • 在此处输入应用程序的ClientID、域和重定向URL。*

对于**App的权限,**粘贴以下XML并创建:

<AppPermissionRequests AllowAppOnlyPolicy="true">
  <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>

字符串



现在点击**Trust it**授予权限:



我在SharePoint站点上传了示例文件



现在,在授予权限后我可以成功打印文件如下所示:

from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext

site_url = "https://xxx.sharepoint.com/sites/testruk"
client_id = "ClientID"
client_secret = "ClientSecret"

ctx = ClientContext(site_url).with_credentials(ClientCredential(client_id, client_secret))

folder_path = 'doc1/folder1'
root_folder = ctx.web.get_folder_by_server_relative_path(folder_path).expand(["Files"]).get().execute_query()
print("root_folder = ", root_folder)

for file in root_folder.files:
    print(file.name)


参考号:

Granting access using SharePoint App-Only

相关问题