Search code examples
pythonazure-active-directoryonedriveoffice365api

How to access Microsoft One Drive with python only using username & password


I'm planing to transfer the files from my linux system to Onedrive. However I implemented it using Microsoft Garph API. But I want to know if I only give username and password, How can I get the access.

For your reference my code

import os
import requests
params = {
          'grant_type': 'refresh_token', 
          'client_id': '',
          'refresh_token': ''
         }

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']
header = {'Authorization': 'Bearer ' + access_token}
directory='./uploads'
upload_url="https://graph.microsoft.com/v1.0/users/username/drive/root:/fotos/HouseHistory"

for root, dirs, files in os.walk(directory):
    for filename in files:
        filepath = os.path.join(root,filename)
        print("Uploading "+filename+"....")
        fileHandle = open(filepath, 'rb')
        r = requests.put(upload_url+"/"+filename+":/content", data=fileHandle, headers=header)
        fileHandle.close()
        if r.status_code == 200 or r.status_code == 201:
            #remove folder contents
            print("succeeded, removing original file...")
            os.remove(os.path.join(root, filename)) 
print("Script completed")
raise SystemExit

How to generate the client ID & refresh token using API if the username & password is given. In addition to that we need to set the permission also like FileReadWrite

May I know what all changes is need in my code for generalizing the script. Only by giving username & password I need to perform all this. Currently I generated the client ID & settled the PERMISSION here manually by

https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Overview

Thanks in advance for your help


Solution

  • As I mentioned in your another post, we cannot use username & password to get the client ID. We should create the Azure AD app in Azure portal, get client ID from there and configure it into your project.

    I notice that you are trying to use refresh_token as the grant_type. That is not correct. Refresh token is used to get a new access token. You could refer to this sample: Refresh the access token.

    You should use authorization code flow to do the authorization. And you will get a refresh token in this step. But it's not what you need in your project. Because you should not use refresh_token as the grant_type here. Only when you need to refresh a new access token, the grant_type should be set to refresh_token.

    Please go through the sample project for more information.