r/learnpython • u/Valuable-Ant3465 • 23h ago
Python Auth to modern Microsoft SPO
Hi all,
I'm doing my student project to upload some files to SPO and struggling with Auth.
This code returns 0 on first ctx, but later fails.
I hope I got all UID right like on the picture
https://i.postimg.cc/ncw71PzR/conf1.png
And this is my code, I also noticed once you used you tenant ID username and password can take any values, is this normal ? I think this all because of modern SPO security, do you think this Auth with ctx is OK, or can do some other way ?
from office365.sharepoint.client_context import ClientContext
# Configuration
site_url = r"https://cbxXXX.sharepoint.com"
tenant = r"4e4d8cb1-f036-446f-bacd-3b711191a7b2"
client_id = r"5c6d0b11-c4da-4897-842a-79b9743d6a23"
username = r'[email protected]
password = r'N0gi123!'
ctx = ClientContext(site_url).with_username_and_password(
tenant, client_id , username, password )
print ('.........2222 bb OK ', ctx)
web = ctx.web.get().execute_query()
print("......... verification check :", web.title)
OUTPUT::::::
.........2222 bb OK <office365.sharepoint.client_context.ClientContext object at 0x0000017CCBCE3B60>
.....
Unhandled exception in listener <bound method SharePointRequest._authenticate_request of <office365.sharepoint.request.SharePointRequest object at 0x0000017CCBCE3CB0>>
File "C:\Python314\Lib\site-packages\office365\runtime\auth\token_response.py", line 61, in from_json
raise ValueError(value)
ValueError: {'error': 'invalid_grant', 'error_description': 'AADSTS50034: The user account {EUII Hidden} does not exist in the 4e4d8cb1-f036-446f-bacd-3b711191a7b2 directory. To sign into this application, the account must be added to the directory. Trace ID: eb657c1d-4806-4557-a49d-f5468c
0
Upvotes
2
u/Massive_Distance_616 22h ago
The error is the useful part: AADSTS50034 means that account doesn’t exist in that tenant’s directory. The address you’re signing in with ends in sharepoint.com, but that’s the site’s domain, not a user sign-in name. Try the account’s actual Microsoft 365 login (the one you use to sign in to Office), which is usually something like [email protected] or your organisation’s own domain.
Your first print works because ClientContext(...) only builds an object. Nothing is authenticated until execute_query() runs, which is why it fails on the next line.
Also, please don’t post a real password in a public thread. If that one is real, change it now. And if the sign-in still fails after the username fix, password logins are often blocked by MFA or tenant security policy, so you may need an app registration instead, which usually needs admin consent on the tenant. I’m not certain which options your library version supports, so check its docs.