Search code examples
pythonpython-3.xexchangelib

How to connect to an exchange server using exchangelib over http proxy and disabling ssl?


Anyone has experience handling proxy support and disabling of SSL for exchangelib? there is a reference for handling of proxy support https://ecederstrand.github.io/exchangelib/#proxies-and-custom-tls-validation but it does not handle disabling of SSL. Tried this code from co-pilot but runs into error :

class CustomProtocol(BaseProtocol):

    def __init__(self, *args,**kwargs):
        self.proxy = kwargs.pop('proxy',None)
        super().__init__(*args, **kwargs)

    def get_adapter(self):
        return NoVerifyHTTPAdapter()

    def init_poolmanager(self, *args, **kwargs):
        kwargs["ssl_context"] = self.get_adapter().ssl_context
        kwargs["proxy"] = self.proxy
        super().init_poolmanager(*args, **kwargs)
    
    def send(self, *args, **kwargs):
    PROXY_URL=environment_variables["PROXY_URL"]
        kwargs["proxies"] = {
        "http": PROXY_URL,
        "https": PROXY_URL,
        }
        return super().send(*args, **kwargs)

BaseProtocol.HTTP_ADAPTER_CLS = CustomProtocol #change to use custom adapter for proxy

I got the following error:

trying to establish connection to exchange server using exchangelib over http proxy and ssl disabled

Solution

  • The implementation of the built-in NoVerifyHTTPAdapter is:

    class NoVerifyHTTPAdapter(requests.adapters.HTTPAdapter):
        """An HTTP adapter that ignores TLS validation errors. Use at own risk."""
    
        def cert_verify(self, conn, url, verify, cert):
            super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
    
        def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
            return super().get_connection_with_tls_context(request=request, verify=False, proxies=proxies, cert=cert)
    

    Combine that with the documented proxy adapter implementation to get your desired functionality.