Skip to content
Advertisement

ExchangeImpersonation SOAP header must be present for this type of OAuth token in Python

Recently Microsoft has withdrawn the basic authentication service for accessing the Exchange Service. Therefore I am working on switching the authentication from basic to OAuth based. However, during the testing, I come across the below exception.

  File "/usr/local/lib/python3.6/site-packages/exchangelib/services/common.py", line 423, in _raise_soap_errors
    raise vars(errors)[code](msg)
exchangelib.errors.ErrorInvalidExchangeImpersonationHeaderData: ExchangeImpersonation SOAP header must be present for this type of OAuth token.

I went through the suggestions mentioned here https://github.com/ecederstrand/exchangelib/issues/735 for solving but had no luck solving the issues.

#Implementation

redentials = OAuth2Credentials(
            client_id=self.client_id, client_secret=self.client_secret, tenant_id=self.tenant_id,
            identity=Identity(smtp_address=self.email_address)
        )
        log.info(f"Credentials ==>{credentials}")
        config = Configuration(server=self.email_server, credentials=credentials,  auth_type=OAUTH2,  version=Version(build=EXCHANGE_O365))
        self.account = Account(self.email_address, access_type=DELEGATE, config=config)

Any suggestion on solving the above exception would be a great help. Thanks in Advance

Advertisement

Answer

When your using the client_credentials flow you need to use impersonation in EWS eg change

access_type=DELEGATE

to

access_type=IMPERSONATION

You also need to make sure you Application registration has the full_access_as_app permission and its consented to see https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement