Exchangelib error in Python: www-authenticate

淺唱寂寞╮ 提交于 2021-01-28 07:05:09

问题


I'm randomly facing an authentication error using library exchangelib:

from exchangelib import DELEGATE, Account, Credentials

creds = Credentials(
    username=username,
    password=pw)

account = Account(
    primary_smtp_address=mailbox_mail,
    credentials=creds,
    autodiscover=True,
    access_type=DELEGATE
)

The definition of the account variable causes the following error, but can't find why or anything useful in the relative documentation:

[2020-09-03 15:00:56,588] {taskinstance.py:1059} ERROR - 'www-authenticate'
Traceback (most recent call last)
  File "/opt/python3.6/lib/python3.6/site-packages/cached_property.py", line 69, in __get_
    return obj_dict[name
KeyError: 'root

During handling of the above exception, another exception occurred

Traceback (most recent call last)
  File "/usr/local/lib/airflow/airflow/models/taskinstance.py", line 930, in _run_raw_tas
    result = task_copy.execute(context=context
  File "/usr/local/lib/airflow/airflow/operators/python_operator.py", line 113, in execut
    return_value = self.execute_callable(
  File "/usr/local/lib/airflow/airflow/operators/python_operator.py", line 118, in execute_callabl
    return self.python_callable(*self.op_args, **self.op_kwargs
  File "/home/airflow/gcs/dags/dg_functions/dg_flash_news_competitiva_mail/fun_flash_news_extract.py", line 34, in flash_news_extractio
    inbox = account.root / 'Top of Information Store' / 'Inbox
  File "/opt/python3.6/lib/python3.6/site-packages/cached_property.py", line 73, in __get_
    return obj_dict.setdefault(name, self.func(obj)
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/account.py", line 270, in roo
    return Root.get_distinguished(account=self
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/roots.py", line 109, in get_distinguishe
    folder=cls(account=account, name=cls.DISTINGUISHED_FOLDER_ID, is_distinguished=True
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/base.py", line 487, in resolv
    folders = list(FolderCollection(account=account, folders=[folder]).resolve()
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/collections.py", line 256, in resolv
    additional_fields=additional_field
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/folders/collections.py", line 319, in get_folder
    shape=ID_ONLY
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/get_folder.py", line 34, in cal
    shape=shape
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 540, in _pool_request
    for elem in self._get_elements(payload=payload_func(chunk, **kwargs))
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 84, in _get_element
    response = self._get_response_xml(payload=payload
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/services/common.py", line 162, in _get_response_xm
    stream=self.streaming
  File "/opt/python3.6/lib/python3.6/site-packages/exchangelib/util.py", line 715, in post_ratelimite
    stream=stream
  File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 578, in pos
    return self.request('POST', url, data=data, json=json, **kwargs
  File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 530, in reques
    resp = self.send(prep, **send_kwargs
  File "/opt/python3.6/lib/python3.6/site-packages/requests/sessions.py", line 650, in sen
    r = dispatch_hook('response', hooks, r, **kwargs
  File "/opt/python3.6/lib/python3.6/site-packages/requests/hooks.py", line 31, in dispatch_hoo
    _hook_data = hook(hook_data, **kwargs
  File "/opt/python3.6/lib/python3.6/site-packages/requests_ntlm/requests_ntlm.py", line 151, in response_hoo
    kwarg
  File "/opt/python3.6/lib/python3.6/site-packages/requests_ntlm/requests_ntlm.py", line 103, in retry_using_http_NTLM_aut
    auth_header_value = response2.headers[auth_header_field
  File "/opt/python3.6/lib/python3.6/site-packages/requests/structures.py", line 54, in __getitem_
    return self._store[key.lower()][1
KeyError: 'www-authenticate

It's strange because this error happens in a way it seems random. When this error occurs I just re-run the code and it immediately works.

I use exchangelib==3.2.0 and Python 3.7.

EDIT: Following you can find an OK log and a KO log:

OK LOG:

2020-09-04 10:12:24 DEBUG    Waiting for autodiscover_cache lock
2020-09-04 10:12:24 DEBUG    autodiscover_cache lock acquired
2020-09-04 10:12:24 DEBUG    Server [server_name]: Created session 29854
2020-09-04 10:12:24 DEBUG    Cache hit for key ([domain_name], Credentials([domaint][user], '********')): https://[server_name]/Autodiscover/Autodiscover.xml
2020-09-04 10:12:24 DEBUG    Server [server_name]: Waiting for session
2020-09-04 10:12:24 DEBUG    Server [server_name]: Got session 29854
2020-09-04 10:12:24 DEBUG    Session 29854 thread 140450161141504: retry 0 timeout 10 POST'ing to https://[server_name]/Autodiscover/Autodiscover.xml after 10s wait
2020-09-04 10:12:24 DEBUG    Starting new HTTPS connection (1): [server_name]:443
2020-09-04 10:12:24 DEBUG    https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0
2020-09-04 10:12:24 DEBUG    https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0
2020-09-04 10:12:24 DEBUG    https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 200 1512
2020-09-04 10:12:24 DEBUG    Retry: 0
Waited: 10
Timeout: 10
Session: 29854
Thread: 140450161141504
Auth type: <requests_ntlm.requests_ntlm.HttpNtlmAuth object at 0x7fbd16c577c0>
URL: https://[server_name]/Autodiscover/Autodiscover.xml
HTTP adapter: <requests.adapters.HTTPAdapter object at 0x7fbd16c576d0>
Allow redirects: False
Streaming: False
Response time: 0.45260270000017044
Status code: 200
Request headers: {'User-Agent': 'exchangelib/3.2.0 (python-requests/2.24.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'Keep-Alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '363', 'Authorization': 'NTLM TlRMTVNTUAADAAAAGAAYAIQAAADcANwAnAAAABAAEABYAAAAHAAcAGgAAAAAAAAAhAAAABAAEAB4AQAANYKJ4gYBsR0AAAAPub38DriCTdGYXyBeyEmnhFcASQBOAEQAUgBPAE8AVABkAGEAdABhAGcAbwB2AGUAcgBuAGEAbgBjAGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5YSqd4DM1UDCWxxNIp33ZQEBAAAAAAAAhiCP86OC1gHUAV9Y4d/fWgAAAAACABAAVwBJAE4ARABSAE8ATwBUAAEADgBXAE0ATwBFAFgAMAA0AAQAGAB3AGkAbgBkAC4AcgBvAG8AdAAuAGkAdAADACgAVwBNAE8ARQBYADAANAAuAHcAaQBuAGQALgByAG8AbwB0AC4AaQB0AAUADgByAG8AbwB0AC4AaQB0AAcACACGII/zo4LWAQYABAACAAAACgAQADeb/GQ6brEyEkTMYIxALRMAAAAAAAAAAGR+d4O+5tqPvV7v0nc4Lxo='}
Response headers: {'Cache-Control': 'private', 'Content-Length': '1512', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Server': 'Microsoft-IIS/8.5', 'Set-Cookie': 'X-BackEndCookie=S-1-5-21-842925246-725345543-1163770773-1933531=u56Lnp2ejJqBy82bmZqeycbSx8ucztLLxsjH0seczJ3SnMjKxprNmpnGyZyZgYHNz83P0s7P0s/Lq87Pxc7NxcrMgY2QkIvRlouBzg==; expires=Sun, 04-Oct-2020 10:12:53 GMT; path=/Autodiscover; secure; HttpOnly', 'Persistent-Auth': 'true', 'request-id': '75ad68fb-99a1-490d-a755-21df9b7dc8d7', 'X-CalculatedBETarget': 'wivex01.[domain_name]', 'X-DiagInfo': 'WIVEX01', 'X-BEServer': 'WIVEX01', 'X-AspNet-Version': '4.0.30319', 'X-Powered-By': 'ASP.NET, ARR/3.0', 'X-FEServer': 'WMOEX04', 'Date': 'Fri, 04 Sep 2020 10:12:24 GMT'}
Request data: b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"><Request><EMailAddress>[mail_address]</EMailAddress><AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema></Request></Autodiscover>'
Response data: b'<?xml version="1.0" encoding="utf-8"?>\r\n<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">\r\n  <Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">\r\n    <User>\r\n      <DisplayName>Servizio Data Governance BDA</DisplayName>\r\n      <LegacyDN>/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=30cb9e003a984ecab16ac41684388a50-Servizio Data Gover</LegacyDN>\r\n      <AutoDiscoverSMTPAddress>[mail_address]</AutoDiscoverSMTPAddress>\r\n      <DeploymentId>a97bb132-fdfa-4fba-876f-79442c336e12</DeploymentId>\r\n    </User>\r\n    <Account>\r\n      <AccountType>email</AccountType>\r\n      <Action>settings</Action>\r\n      <MicrosoftOnline>False</MicrosoftOnline>\r\n      <Protocol>\r\n        <Type>EXCH</Type>\r\n        <Server>9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]</Server>\r\n        <ServerDN>/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]</ServerDN>\r\n        <ServerVersion>73C186B1</ServerVersion>\r\n        <MdbDN>/o=Wind/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=9dd010c4-db51-45e2-a8b8-1d37b45950ef@[domain_name]/cn=Microsoft Private MDB</MdbDN>\r\n        <PublicFolderServer>[public_server]</PublicFolderServer>\r\n        <AD>DCIVWR07.[domain_name]</AD>\r\n        <ASUrl>https://[public_server_name]/EWS/Exchange.asmx</ASUrl>\r\n        <EwsUrl>https://[public_server_name]/EWS/Exchange.asmx</EwsUrl>\r\n        <EmwsUrl>https://[public_server_name]/EWS/Exchange.asmx</EmwsUrl>\r\n        <SharingUrl>https://[public_server_name]/EWS/Exchange.asmx</SharingUrl>\r\n        <EcpUrl>https://[public_server_name]/owa/</EcpUrl>\r\n        <EcpUrl-um>?path=/options/callanswering</EcpUrl-um>\r\n        <EcpUrl-aggr>?path=/options/connectedaccounts</EcpUrl-aggr>\r\n        <EcpUrl-mt>options/ecp/PersonalSettings/DeliveryReport.aspx?rfr=olk&amp;exsvurl=1&amp;IsOWA=&lt;IsOWA&gt;&amp;MsgID=&lt;MsgID&gt;&amp;Mbx=&lt;Mbx&gt;&amp;realm=[realm]</EcpUrl-mt>\r\n        <EcpUrl-ret>?path=/options/retentionpolicies</EcpUrl-ret>\r\n        <EcpUrl-sms>?path=/options/textmessaging</EcpUrl-sms>\r\n        <EcpUrl-photo>?path=/options/myaccount/action/photo</EcpUrl-photo>\r\n        <EcpUrl-tm>options/ecp/?rfr=olk&amp;ftr=TeamMailbox&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tm>\r\n        <EcpUrl-tmCreating>options/ecp/?rfr=olk&amp;ftr=TeamMailboxCreating&amp;SPUrl=&lt;SPUrl&gt;&amp;Title=&lt;Title&gt;&amp;SPTMAppUrl=&lt;SPTMAppUrl&gt;&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tmCreating>\r\n        <EcpUrl-tmEditing>options/ecp/?rfr=olk&amp;ftr=TeamMailboxEditing&amp;Id=&lt;Id&gt;&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tmEditing>\r\n        <EcpUrl-extinstall>?path=/options/manageapps</EcpUrl-extinstall>\r\n        <OOFUrl>https://[public_server_name]/EWS/Exchange.asmx</OOFUrl>\r\n        <UMUrl>https://[public_server_name]/EWS/UM2007Legacy.asmx</UMUrl>\r\n        <OABUrl>https://[public_server_name]/OAB/95ecfb44-4ba6-46e0-88b1-8a6622de13e8/</OABUrl>\r\n        <ServerExclusiveConnect>off</ServerExclusiveConnect>\r\n      </Protocol>\r\n      <Protocol>\r\n        <Type>EXPR</Type>\r\n        <Server>[public_server_name]</Server>\r\n        <SSL>On</SSL>\r\n        <AuthPackage>Ntlm</AuthPackage>\r\n        <ASUrl>https://[public_server_name]/EWS/Exchange.asmx</ASUrl>\r\n        <EwsUrl>https://[public_server_name]/EWS/Exchange.asmx</EwsUrl>\r\n        <EmwsUrl>https://[public_server_name]/EWS/Exchange.asmx</EmwsUrl>\r\n        <SharingUrl>https://[public_server_name]/EWS/Exchange.asmx</SharingUrl>\r\n        <EcpUrl>https://[public_server_name]/owa/</EcpUrl>\r\n        <EcpUrl-um>?path=/options/callanswering</EcpUrl-um>\r\n        <EcpUrl-aggr>?path=/options/connectedaccounts</EcpUrl-aggr>\r\n        <EcpUrl-mt>options/ecp/PersonalSettings/DeliveryReport.aspx?rfr=olk&amp;exsvurl=1&amp;IsOWA=&lt;IsOWA&gt;&amp;MsgID=&lt;MsgID&gt;&amp;Mbx=&lt;Mbx&gt;&amp;realm=[realm]</EcpUrl-mt>\r\n        <EcpUrl-ret>?path=/options/retentionpolicies</EcpUrl-ret>\r\n        <EcpUrl-sms>?path=/options/textmessaging</EcpUrl-sms>\r\n        <EcpUrl-photo>?path=/options/myaccount/action/photo</EcpUrl-photo>\r\n        <EcpUrl-tm>options/ecp/?rfr=olk&amp;ftr=TeamMailbox&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tm>\r\n        <EcpUrl-tmCreating>options/ecp/?rfr=olk&amp;ftr=TeamMailboxCreating&amp;SPUrl=&lt;SPUrl&gt;&amp;Title=&lt;Title&gt;&amp;SPTMAppUrl=&lt;SPTMAppUrl&gt;&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tmCreating>\r\n        <EcpUrl-tmEditing>options/ecp/?rfr=olk&amp;ftr=TeamMailboxEditing&amp;Id=&lt;Id&gt;&amp;exsvurl=1&amp;realm=[realm]</EcpUrl-tmEditing>\r\n        <EcpUrl-extinstall>?path=/options/manageapps</EcpUrl-extinstall>\r\n        <OOFUrl>https://[public_server_name]/EWS/Exchange.asmx</OOFUrl>\r\n        <UMUrl>https://[public_server_name]/EWS/UM2007Legacy.asmx</UMUrl>\r\n        <OABUrl>https://[public_server_name]/OAB/95ecfb44-4ba6-46e0-88b1-8a6622de13e8/</OABUrl>\r\n        <ServerExclusiveConnect>on</ServerExclusiveConnect>\r\n        <CertPrincipalName>msstd:wmae.[cert].it</CertPrincipalName>\r\n        <EwsPartnerUrl>https://[public_server_name]/EWS/Exchange.asmx</EwsPartnerUrl>\r\n        <GroupingInformation>STMOLFETTA</GroupingInformation>\r\n      </Protocol>\r\n      <Protocol>\r\n        <Type>WEB</Type>\r\n        <Internal>\r\n          <OWAUrl AuthenticationMethod="Basic, Fba">https://[public_server_name]/owa/</OWAUrl>\r\n          <Protocol>\r\n            <Type>EXCH</Type>\r\n            <ASUrl>https://[public_server_name]/EWS/Exchange.asmx</ASUrl>\r\n          </Protocol>\r\n        </Internal>\r\n        <External>\r\n          <OWAUrl AuthenticationMethod="Fba">https://[public_server_name]/owa/</OWAUrl>\r\n          <Protocol>\r\n            <Type>EXPR</Type>\r\n            <ASUrl>https://[public_server_name]/EWS/Exchange.asmx</ASUrl>\r\n          </Protocol>\r\n        </External>\r\n      </Protocol>\r\n    </Account>\r\n  </Response>\r\n</Autodiscover>'

2020-09-04 10:12:24 DEBUG    No retry: wrong status code 200
2020-09-04 10:12:24 DEBUG    Session 29854 thread 140450161141504: Useful response from https://[server_name]/Autodiscover/Autodiscover.xml
2020-09-04 10:12:24 DEBUG    Server [server_name]: Releasing session 29854
2020-09-04 10:12:24 INFO     Step 5: Checking response
2020-09-04 10:12:24 DEBUG    Released autodiscover_cache_lock
2020-09-04 10:12:24 DEBUG    Waiting for _protocol_cache_lock
2020-09-04 10:12:24 DEBUG    Protocol __call__ cache miss. Adding key '('https://[public_server_name]/EWS/Exchange.asmx', Credentials('[domain]\[user]', '********'))'
2020-09-04 10:12:24 DEBUG    Requesting b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2019"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>[domain]\[user]</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>' from https://[public_server_name]/EWS/Exchange.asmx
2020-09-04 10:12:24 DEBUG    Trying to get service auth type for https://[public_server_name]/EWS/Exchange.asmx
2020-09-04 10:12:24 DEBUG    Starting new HTTPS connection (1): [public_server_name]:443
2020-09-04 10:12:24 DEBUG    https://[public_server_name]:443 "POST /EWS/Exchange.asmx HTTP/1.1" 401 0
2020-09-04 10:12:24 DEBUG    Request headers: {'User-Agent': 'exchangelib/3.2.0 (python-requests/2.24.0)', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '466'}
2020-09-04 10:12:24 DEBUG    Response headers: {'Server': 'Microsoft-IIS/8.5', 'WWW-Authenticate': 'Negotiate, NTLM', 'request-id': '5035ba0e-5caf-4b3d-8c39-07f76e04a0da', 'X-Powered-By': 'ASP.NET, ARR/3.0', 'X-FEServer': 'WIVEX02', 'Date': 'Fri, 04 Sep 2020 10:12:24 GMT', 'Content-Length': '0'}
2020-09-04 10:12:24 DEBUG    Auth type is NTLM
2020-09-04 10:12:24 DEBUG    Server [public_server_name]: Created session 25722
2020-09-04 10:12:24 DEBUG    Added account: [account_mail]

KO LOG:

2020-09-04 09:58:47 DEBUG    Waiting for autodiscover_cache lock
2020-09-04 09:58:47 DEBUG    autodiscover_cache lock acquired
2020-09-04 09:58:47 DEBUG    Server [server_name]: Created session 26384
2020-09-04 09:58:47 DEBUG    Cache hit for key ([domain_name], Credentials([domaint][user], '********')): https://[server_name]/Autodiscover/Autodiscover.xml
2020-09-04 09:58:47 DEBUG    Server [server_name]: Waiting for session
2020-09-04 09:58:47 DEBUG    Server [server_name]: Got session 26384
2020-09-04 09:58:47 DEBUG    Session 26384 thread 140624867845888: retry 0 timeout 10 POST'ing to https://[server_name]/Autodiscover/Autodiscover.xml after 10s wait
2020-09-04 09:58:47 DEBUG    Starting new HTTPS connection (1): [server_name]:443
2020-09-04 09:58:48 DEBUG    https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 401 0
2020-09-04 09:58:48 DEBUG    https://[server_name]:443 "POST /Autodiscover/Autodiscover.xml HTTP/1.1" 502 1477
2020-09-04 09:58:48 ERROR    KeyError: 'www-authenticate'
Retry: 0
Waited: 10
Timeout: 10
Session: 26384
Thread: 140624867845888
Auth type: <requests_ntlm.requests_ntlm.HttpNtlmAuth object at 0x7fe5c41a37c0>
URL: https://[server_name]/Autodiscover/Autodiscover.xml
HTTP adapter: <requests.adapters.HTTPAdapter object at 0x7fe5c41a36d0>
Allow redirects: False
Streaming: False
Response time: 0.3348593030000302
Status code: 503
Request headers: {'Content-Type': 'text/xml; charset=utf-8', 'Accept-Encoding': 'gzip, deflate'}
Response headers: {}
Request data: b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"><Request><EMailAddress>[email_address]</EMailAddress><AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema></Request></Autodiscover>'
Response data: b''

2020-09-04 09:58:48 DEBUG    Server [server_name]: Retiring session 26384
2020-09-04 09:58:48 DEBUG    Server [server_name]: Created session 26493
2020-09-04 09:58:48 DEBUG    Server [server_name]: Releasing session 26493

Please, can someone help me?


回答1:


I just pushed a commit that might fix this for you: https://github.com/ecederstrand/exchangelib/commit/c7b4b5a89c5518a6d19b7e88c5a945b9083b15d0

You need to use it in combination with a retry policy to paper over this internal error from requests_ntlm.



来源:https://stackoverflow.com/questions/63726671/exchangelib-error-in-python-www-authenticate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!