13,721 questions
Trying to write a python script to automate uploading files to One Drive
Evan Walter
5
Reputation points
I have an App Registered with a Client id and Client Secret. If I look under API Permissions I have Sites.FilesReadWrite.All and Files.ReadWrite.All and others both delegated and application.
I've got this method to get an auth_code:
def get_access_token(client_id, client_secret, tenant_id, scopes):
# Create a PublicClientApplication object
pca = msal.ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=f"https://login.microsoftonline.com/{tenant_id}"
)
# Acquire a token using the client credentials flow
result = pca.acquire_token_for_client(scopes=scopes)
# Check if the access token was successfully obtained
if "access_token" in result:
access_token = result["access_token"]
return access_token
else:
print("Failed to acquire access token.")
if "error" in result:
print("Error:", result["error"])
if "error_description" in result:
print("Error description:", result["error_description"])
return None
It works if I use pass in scopes = ["https://graph.microsoft.com/.default"] (but not
scopes = ["Files.ReadWrite.All"]), and returns an auth code.
I then try:
headers = { 'Authorization': 'Bearer ' + access_token }
file_path = "...my file"
with open(file_path, 'rb') as upload:
media_content = upload.read()
response=requests.put(GRAPH_API_ENDPOINT + f'/me/drive/items/root:/{file_name}:/content',
headers=headers,
data=media_content
)
print(response.json())
It responds:
{'error': {'code': 'BadRequest', 'message': '/me request is only valid with delegated authentication flow.', ....
And if I try:
url ="https://graph.microsoft.com/v1.0/users/%s"%MY_ACCOUNT
response = requests.get(url,headers=headers)
response.json()
"""
responds
'error': {'code': 'Request_ResourceNotFound',
'message': "Resource '...MY Account ..' does not exist or one of its queried reference-property objects are not present.",...
"""
Microsoft Security Microsoft Graph
Sign in to answer