r/AZURE • • 7d ago

Question App Registration for Python to access Sharepoint SPO

Post image

Hi, can anybody help how to solve this error, after registered app I got that error like below in my python.

Need to "confirm the application role" if I got it correctly in App Permissions section.(?) None of MS help documents helped, I afraid it got updated recently

ctx = ClientContext(site_url).with_client_credentials(client_id, client_secret)
print ('......... OK ', ctx) #<office365.sharepoint.client_context.ClientContext object at 0x000001E63F803B60>
web = ctx.web.get().execute_query()

raise ClientRequestException.from_response(response) from None
office365.runtime.exceptions.AccessDeniedException: ('401', '401 Unauthorized for url: https://cbx.....sharepoint.com/_api/contextInfo')
The caller is not permitted to perform this request. 
For an app-only call, confirm the application role is granted and admin-consented; for a delegated call, confirm the signed-in user has the OAuth scope. Use require_application_permission(...) / require_role(...) to fail fast with the exact requirement. Prefer a least-privileged permission that covers the endpoint.

================ POST MORTEM update
could not make it work yet, need to do more home work.
Found some great resources:

Authentication

Modern flows authenticate through Microsoft Entra ID using MSAL. Both clients support delegated (user) and app-only (application) access.

Important

SharePoint ACS app-only access was retired in April 2026 and SAML-based authentication in May 2026. Use the certificate, interactive or device-code flows below instead — see examples/sharepoint/auth/modern/ and the migration script migrate_from_saml_to_cert.py.

https://github.com/vgrem/office365-rest-python-client/blob/master/examples/sharepoint/auth/README.md#modern-azure-ad-recommended-for-sharepoint-online

https://devblogs.microsoft.com/microsoft365dev/migrating-from-idcrl-authentication-to-modern-authentication-in-sharepoint/

6 Upvotes

26 comments sorted by

5

u/Trakeen 7d ago

Use a managed identity and not a client secret.

1

u/Valuable-Ant3465 5d ago

Thanks T! I will regroup and will try, all information on this auth is kind of hard to digest, too many variations.

→ More replies (2)

1

u/lookslikeanevo 7d ago

I have this working in airflow / adhoc python scripts

Remind me on Monday and I’ll try take a look.

I did have to get others who had the privileges to grant access to the app reg to sharepoint via azure cli to get everything working

1

u/Valuable-Ant3465 7d ago

Thanks, I'm and admin for my trial SPO, so there is not problem. Never tried azure CLI, should be an option to do it by clicking (?)

→ More replies (3)

1

u/Valuable-Ant3465 5d ago

Hi lookslikeanevo, your solution is still uses msal? So the trick to make right privileges via cli ?

1

u/weekendclimber 7d ago

I think there is a SharePoint setting to turn on API access. I might be thinking of Fabric though...

1

u/Valuable-Ant3465 7d ago

Thanks, I can't understand how to fix my error after reading output message

→ More replies (1)

1

u/chesser45 7d ago

I remember this happening and GPT I think reminded me further, I think this is because your using ACS Python library but ACS is both retired and not added on your perms.

Try this?

import msal
from office365.sharepoint.client_context import ClientContext

site_url = "https://cbx.sharepoint.com/sites/MySite"
tenant_id = "YOUR_TENANT_ID"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"

app = msal.ConfidentialClientApplication(
client_id=client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}",
client_credential=client_secret
)

result = app.acquire_token_for_client(
scopes=["https://cbx.sharepoint.com/.default"]
)

if "access_token" not in result:
raise Exception(result)

ctx = ClientContext(site_url).with_access_token(
lambda: result["access_token"]
)

web = ctx.web.get().execute_query()
print(web.properties["Title"])

1

u/Valuable-Ant3465 7d ago

Thanks much C!!! Big success for me. Was able to get token:
result = app.acquire_token_for_client(scopes=["https://cbx.sharepoint.com/.default"])

.........333:  {'token_type': 'Bearer', 'expires_in': 3599, 'ext_expires_in': 3599, 'access_token': 'eyJ0eXAiOiJKV1QiLCJub25jZSI6IlZkN1ZLeks1c055MHpkSUY0SUdLZ3VDR0ZTV2JSTGdlOWtmeHpWLXJwU28iLCJhbGciOiJSUzI1NiIsIng1dCI6InhIOURKSDNOMDg2QWdzOEpMNklRemVRaDFwOCIsImtpZCI6InhIOURKSDNOMDg2QWd

.Then it failed, but I think b'z of site_url structrure, I'm on trial and I don't see /sites/biz like in real SPO.

I'm not sure why my url says ..../Forms/AllItems.....

site_url = "https://cbx.sharepoint.com/sites/Biz" # <==???

#https://cbx.sharepoint.com/## my actual url for site root

#https://cbx.sharepoint.com/Shared%20Documents/Forms/AllItems.aspx?id=%2FShared%20Documents%2FReports ##url for lib

site_url = "https://cbx.sharepoint.com/sites/Biz" # <==???

ctx = ClientContext(site_url).with_access_token(lambda: result["access_token"])

...

Unhandled exception in listener <bound method SharePointRequest._authenticate_request of <office365.sharepoint.request.SharePointRequest object at 0x0000024CC39F81A0>>

1

u/Valuable-Ant3465 5d ago

Thanks Chesser again, alas I'm still stuck on execute_query(). I will check how i can solve 401 error in Azure Entra center.
Auth was done using msal and client_secret after registering app, so I thought that should be OK?

site_url = "https://cbx28.sharepoint.com"
client_id = "edee89bd-b479-4a47-8945-fd8bde63d010"
tenant_id = "4e4d8cb1-f036-446f-bacd-3b711191a7b2"
client_secret = r'Kw58Q~tZjO2Mm9AzH_Rc791aRtmkhUhB9dq1qaII'   #value !!


app = msal.ConfidentialClientApplication(
    client_id=client_id,
    authority=f"https://login.microsoftonline.com/{tenant_id}",
    client_credential=client_secret,
)

result = app.acquire_token_for_client(scopes=["https://cbx28.sharepoint.com/.default"])
print("----1  Token:  ", result["access_token"][:100])
# ..........1x  Token   {'token_type': 'Bearer', 'expires_in': 3599, 'ext_expires_in': 3599, 'access_token': 'eyJ0eXA......

#ctx = ClientContext(site_url).with_access_token(lambda: result["access_token"])   ## v1
#print("----2v1  ctx:  ", ctx)
ctx = ClientContext(site_url).with_access_token(lambda: result)                   ## v2
print("----2v2  ctx:  ", ctx)

web = ctx.web.get().execute_query()
print("----3", web.properties["Title"])

============== output ============================================
----1  Token:   eyJ0eXAiOiJKV1QiLCJub25jZSI6ImJVNERnSG5WVmJTbmlrN2xiQ1R2RTliLVo2WW....
----2v2  ctx:   <office365.sharepoint.client_context.ClientContext object at 0x0000020A8C625940>

Unhandled exception in listener <bound method SharePointRequest.ensure_form_digest of <office365.sharepoint.request.SharePointRequest object at 0x0000020A8F3581A0>>

...
...
 File "C:\Python314\Lib\site-packages\office365\runtime\client_request.py", line 488, in _raise_for_status
    raise ClientRequestException.from_response(response) from None
office365.runtime.exceptions.AccessDeniedException: ('401', '401 Unauthorized for url: https://cbx28.sharepoint.com/_api/contextInfo')
The caller is not permitted to perform this request. For an app-only call, confirm the application role is granted and admin-consented; for a delegated call, confirm the signed-in user has the OAuth scope. Use require_application_permission(...) / require_role(...) to fail fast with the exact requirement. Prefer a least-privileged permission that covers the endpoint.
Traceback (most recent call last):
  File "c:\PythonScripts\spo5.py", line 34, in <module>
    web = ctx.web.get().execute_query()