Reputation: 31
I'm trying to read the content of an Excel file stored in OneDrive, via the Sharepoint python API. I've seen a couple of examples for usr/pwd authentication, but none using app credentials (client_id/client_secret).
(1) I created credentials on the sharepoint site using
https://MYDOMAIN.sharepoint.com/sites/engineering/_layouts/15/appregnew.aspx
(2) I gave permissions to the credentials using:
https://MYDOMAIN-admin.sharepoint.com/_layouts/15/appinv.aspx
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" />
</AppPermissionRequests>
(3) Then I tried the following code snippet:
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.client_context import ClientCredential
# sharepoint app: https://outlyer.sharepoint.com/sites/engineering/_layouts/15/appregnew.aspx
client_id = "..."
client_secret = "..."
site_url = "https://MYDOMAIN.sharepoint.com/"
client_credentials = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(client_credentials)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))
This returns an authentication error:
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://MYDOMAIN.sharepoint.com/_api/Web
Any ideas? The MS docs are super cryptic to me, especially as they are apparently many different scopes / methods where app permissions can be handled.
Upvotes: 0
Views: 618
Reputation: 31
Thanks you the suggestion RaytheonXie-MSFT, I was not familiar with the shareplum library. I did get it to work using the code snippet below, but still would like to understand what the actual problem with the msal library is?
# connect to MS365 Graph API (get access token headers), while
# disabling SSL cert verification & suppressing resulting warning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
application = ConfidentialClientApplication(
client_id=CONF["azure"]["client_id"],
client_credential=CONF["azure"]["client_secret"],
authority=f"https://login.microsoftonline.com/{CONF['azure']['tenant_id']}",
verify=False,
)
SCOPE = "https://graph.microsoft.com/.default"
result = application.acquire_token_for_client(scopes=[SCOPE])
access_token = result["access_token"]
headers = {
"Authorization": "Bearer " + access_token,
"Accept": "application/json",
"Content-Type": "application/json",
}
# Because of the SSL issue, we cannot use the MS Graph SDK for queries
# Construct direct URL API queries instead, and secure with certifi
# https://urllib3.readthedocs.io/en/1.26.x/user-guide.html#ssl
# use http.request() to make API calls
http = urllib3.PoolManager(cert_reqs="CERT_REQUIRED", ca_certs=certifi.where())
Upvotes: 0