首页 > 解决方案 > 身份验证 OneDrive API Python

问题描述

使用来自 GitHub 的代码示例,该代码示例专门用于为 Python 访问 OneDrive API 设置身份验证(我开始认为此源已过时),我未能使其超过执行后粘贴 Microsoft 提供的代码的部分程序..

Python代码:

import onedrivesdk

redirect_uri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
client_secret = '*this code omitted*'
client_id='*this code omitted*'
api_base_url='https://api.onedrive.com/v1.0/'
scopes=['onedrive.readwrite']

http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
    http_provider=http_provider,
    client_id=client_id,
    scopes=scopes)

client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
# Ask for the code
print('Paste this URL into your browser, approve the app\'s access.')
print('Copy everything in the address bar after "code=", and paste it below.')
print(auth_url)
code = raw_input('Paste code here: ')

client.auth_provider.authenticate(code, redirect_uri, client_secret)

在浏览器中执行代码并粘贴 url 后,会出现一个弹出窗口,我在其中确认我想让我的应用程序访问 API。我点击“确定”。

然后我会在 URL 任务栏中看到代码。我将代码复制并粘贴到程序中..

然后我得到的错误是:

    raise Exception(str(message["error"]))

Exception: invalid_request

使用的 GitHub 源链接:https ://github.com/OneDrive/onedrive-sdk-python

注意:我不得不省略此列表中的前两个范围:

scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

因为它们显然不存在(根据 Microsoft 在将 URL 粘贴到任务栏后提供的错误代码)

是否有更好的来源为 Python 程序设置身份验证以与 OneDrive API 通信?

我是一个相对较新的 Python 用户,感谢您的耐心等待。

标签: pythonapiauthenticationonedrive

解决方案


我遇到了同样的问题,解决方案是将 redirect_uri 包含在应用程序注册中。

这可以在https://portal.azure.com/和 Azure Active Directory > 应用程序注册 > “您的应用程序”> 身份验证中完成。就我而言,我需要将http://localhost:8080/添加到重定向 URI。

我在这里找到了建议:

https://github.com/OneDrive/onedrive-sdk-python/issues/98

希望它可以帮助某人节省一些时间。


推荐阅读