Использование токен-кода при доступе к OneDrive с использованием Python - PullRequest
0 голосов
/ 13 марта 2019

Я пишу код для перемещения файлов в OneDrive (учетная запись предприятия).Мое приложение проходит проверку подлинности в Azure AD и должно иметь правильный доступ (Files.ReadWrite.All в MS Graph, Sites.ReadWrite.All в Office365 SPO и User.Read в Azure AD).

Код для получениямаркер приложения работает нормально:

import msal

client_id = 'dc185bb*************6bcda94'
authority_host_uri = 'https://login.microsoftonline.com'
discovery_uri = 'https://api.office.com/discovery/'
client_secret = 'VsY7vV**************ToiA0='
tenant = '4a6*********************65079'
authority_uri = authority_host_uri + '/' + tenant
scopes=['https://graph.microsoft.com/.default']

app = msal.ConfidentialClientApplication(
    client_id=client_id, authority=authority_uri,
    client_credential=client_secret)

result = app.acquire_token_for_client(scopes=scopes)
print(result)

Однако, когда я пытаюсь использовать этот токен с библиотекой OneDrive SDK, кажется, что я не могу передать его через:

def __init__(self, http_provider, client_id=None, scopes=None, access_token=None, session_type=None, loop=None,
             auth_server_url=None, auth_token_url=None):
    """Initialize the authentication provider for authenticating
    requests sent to OneDrive

    Args:
        http_provider (:class:`HttpProviderBase<onedrivesdk.http_provider_base>`):
            The HTTP provider to use for all auth requests
        client_id (str): Defaults to None, the client id for your
            application
        scopes (list of str): Defaults to None, the scopes 
            that are required for your application
        access_token (str): Defaults to None. Not used in this implementation.

выше взято из auth_provider.py части onedrivesdk, и ясно указывает, что access_token не используется в реализации.

Есть ли другой способ обойти это?Или другие библиотеки для использования?

1 Ответ

0 голосов
/ 13 марта 2019

Вы можете попробовать использовать эту аутентификацию OneDrive для бизнеса .

import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest

redirect_uri = 'http://localhost:8080'
client_id = your_client_id
client_secret = your_client_secret
discovery_uri = 'https://api.office.com/discovery/'
auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize'
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'

http = onedrivesdk.HttpProvider()
auth = onedrivesdk.AuthProvider(http,
                                client_id,
                                auth_server_url=auth_server_url,
                                auth_token_url=auth_token_url)
auth_url = auth.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
auth.authenticate(code, redirect_uri, client_secret, resource=discovery_uri)
# If you have access to more than one service, you'll need to decide
# which ServiceInfo to use instead of just using the first one, as below.
service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0]
auth.redeem_refresh_token(service_info.service_resource_id)
client = onedrivesdk.OneDriveClient(service_info.service_resource_id + '/_api/v2.0/', auth, http)

Загрузить элемент:

returned_item = client.item(drive='me', id='root').children['newfile.txt'].upload('./path_to_file.txt')

Дополнительные примеры можно найтина эту ссылку .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...