Office365-REST-Python-Client icon indicating copy to clipboard operation
Office365-REST-Python-Client copied to clipboard

I'm having an issu with ClientContext().with_client_certificate function

Open BakaShiba opened this issue 2 years ago • 3 comments

Hello, For the context i'm trying to connect to a Sharepoint by using a Microsoft entra app, will using a certificat. Here the function :

def connect_sharepoint(site_url, client_id, thumbprint, cert_path): try: app_settings = { 'url': site_url,
'client_id': client_id, 'thumbprint': thumbprint, 'certificate_path':cert_path}

    ctx = ClientContext(site_url).with_client_certificate(app_settings['url'],
                                         app_settings['client_id'],
                                         app_settings['thumbprint'],
                                         app_settings['certificate_path'])
    
    web = ctx.web
    ctx.load(web)
    print(ctx)
    ctx.execute_query()
    print("Connection established")
    return ctx
except Exception as e:
    print(f"Connection failed: {str(e)}")
    return None

And it keep returning me this error : Connection failed: 'charmap' codec can't decode byte 0x8d in position 230: character maps to

The actual site url is strored like that : site_url = 'https://domain_name.sharepoint.com/' I'll be glad if you have any advice or solutions ^^

BakaShiba avatar Oct 18 '23 09:10 BakaShiba

Hi there,

it appears the error occurs since certificate file encoding could not be properly determined, this thread reveals a more details.

There is alternative option available for passing certificate, via private_key argument instead of certificate_path as demonstrated below

cert_path = "./selfsignkey.pem"
with open(cert_path, "r") as f:
    private_key = open(cert_path).read()

cert_credentials = {
    "tenant": tenant,
    "client_id": client_id,
    "thumbprint": cert_thumbprint,
    "private_key": private_key,
}
ctx = ClientContext(test_site_url).with_client_certificate(**cert_credentials)
current_web = ctx.web.get().execute_query()

vgrem avatar Oct 19 '23 07:10 vgrem

Thanks a lot for your reply I'll try it ! ^^

BakaShiba avatar Oct 19 '23 08:10 BakaShiba

Hi, i finally manage to download the file but there is strange output.. It's telling me that the download failed with an error "400 client error" but i can see that the file is downloaded on my computer but it's empty and when i try to open it it's telling me that the format or extansion is incorrect :/ Do you have any idea ?

BakaShiba avatar Oct 23 '23 09:10 BakaShiba