我有一个Python脚本,它在一台AWS EC2 Ubuntu机器上定期运行。
此脚本从一些文件中读取数据,有时还会更改其中的数据。
我想从OneDrive下载这些文件,用它们做我自己的事情,然后把它们上传回OneDrive。
我希望这是自动完成的,而不需要用户批准任何登录或凭证。我可以做一次(即在第一次运行时批准登录),但其余的必须自动运行,而不会再次要求批准(当然,除非权限发生变化)。
做这件事最好的方法是什么?
我一直在阅读有关Microsoft Graph API的文档,但我正在努力解决身份验证部分。我已经在Azure AAD中创建了一个应用程序,提供了示例权限(用于测试),并创建了一个秘密凭证。
发布于 2019-10-07 01:03:25
我设法做到了。我不确定这是否是最好的方法,但现在它正在发挥作用。它每小时自动运行一次,我不需要触摸它。
我关注了https://docs.microsoft.com/en-gb/azure/active-directory/develop/v2-oauth2-auth-code-flow上的信息
这就是我所做的。
Azure门户
Web
看起来像是第一次获得令牌,我们必须使用浏览器或模拟类似的东西。
必须有一种程序化的方法来做到这一点,但我不知道如何做到这一点。我也考虑过使用Selenium,但由于只有一次,而且我的应用程序每小时都会请求令牌(保持令牌的新鲜度),所以我放弃了这个想法。
如果我们添加新的权限,我们已有的令牌将失效,我们必须重新执行此手动部分。
该URL将重定向到您设置的重定向URI,并在URL中包含一个code=something。复印一下。
端点:https://login.microsoftonline.com/common/oauth2/v2.0/token
表单URL: grant_type=authorization_code&client_id=your_app_client_id&code=use_the_code_returned_on_previous_step
这将返回一个访问令牌和一个刷新令牌。将刷新令牌存储在某个位置。我要把它保存在一个文件里。
Python
# Build the POST parameters
params = {
'grant_type': 'refresh_token',
'client_id': your_app_client_id,
'refresh_token': refresh_token_that_you_got_in_the_previous_step
}
response = requests.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', data=params)
access_token = response.json()['access_token']
new_refresh_token = response.json()['refresh_token']
# ^ Save somewhere the new refresh token.
# I just overwrite the file with the new one.
# This new one will be used next time.
header = {'Authorization': 'Bearer ' + access_token}
# Download the file
response = requests.get('https://graph.microsoft.com/v1.0/me/drive/root:' +
PATH_TO_FILE + '/' + FILE_NAME + ':/content', headers=header)
# Save the file in the disk
with open(file_name, 'wb') as file:
file.write(response.content)所以基本上,我总是更新刷新令牌。
我使用该Refresh Token调用令牌端点,API为我提供了一个在当前会话期间使用的访问令牌和一个新的Refresh Token。
我会在下一次运行程序时使用这个新的刷新标记,以此类推。
发布于 2020-05-14 23:08:17
Python库可以帮助做到这一点:
pip install cloudsync
然后:
import cloudsync
prov = cloudsync.create_provider("onedrive")
creds = prov.authenticate()
prov.connect(creds)
with open("/my/local/file", "wb") as f:
prov.download_path("/path/to/file/on/onedrive", f):https://stackoverflow.com/questions/58171733
复制相似问题