Microsoft-Graph: Failing to get token from python code: Error SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]

Viewed 647

I need to call a web API. For that I need a bearer token.

I am using databricks(python) code to first get authenticated over Microsoft AAD. Then get bearer token for my service_user. I Followed the microsoft docs docs

But facing problem where it hits our Company server and asking for SSL certificate.

I can't install any certificate. What could be a better way to avoid it. Below is my short code taken from above microsoft and Git repos. but its not working.

Can i get help!

clientId = "42xx-xx-xx5f"
authority = "https://login.microsoftonline.com/tenant_id/"
app = msal.PublicClientApplication(client_id=clientId, authority=authority)
user = "serviceuser@company.com"
pwd = "password"
scope = "Directory.Read.All"

result = app.acquire_token_by_username_password(scopes=[scope], username=user, password=pwd)
print(result)

Got below error

HTTPSConnectionPool(host='mycompany.com', port=443): Max retries exceeded with url: /adfs/services/trust/mex (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)')))
2 Answers

The problem is that the code uses the requests library that relies on the certifi package instead of using Linux certificate chain (so existing instructions doesn't work). To solve that problem it's better to use cluster init script that will install SSL certificate when cluster starts. Something like this (requests and certifi are installed by default), just replace CERT_FILE with actual path to the .pem file with CA certificate:

CERT_FILE="/dbfs/....."
CERTIFI_HOME="$(python -m certifi 2>/dev/null)"
cat $CERT_FILE >> $CERTIFI_HOME

Thank you Indranil. Posting your suggestion as an answer to help other community members.

It's not recommended to use verify = False in your organization's environments because it will disable the SSL verification.

Sometimes, when you are behind a company proxy, it replaces the certificate chain with the ones of Proxy. Adding the certificates in cacert.pem used by certifi should solve the issue.

  1. Find the path where cacert.pem is located:

    Install certifi, if you don't have. Command: pip install certifi

    import certifi
    certifi.where()
    C:\\Users\\[UserID]\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\certifi\\cacert.pem```
    
    
  2. Open the URL on a browser. Download the chain of certificates from the URL and save as Base64 encoded .cer files.

  3. Now open the cacert.pem in a notepad and just add every downloaded certificate contents (---Begin Certificate--- *** ---End Certificate---) at the end.

You can refer to Unable to get local issuer certificate when using requests in python, SSL: CERTIFICATE_VERIFY_FAILED and "unable to get local issuer certificate" when trying to access Microsoft Graph

Related