Imap authentication of a registered app fails with acquired access token.
Simon Nigg
0
Reputation points
I would like to access office365 emails from within a python script.
I am able to acquire an access_token but the subsequent authentication call (using imaplib) fails with (imaplib debug output):
51:24.89 > b'LIBE1 AUTHENTICATE XOAUTH2'
51:24.91 < b'+ '
51:24.91 write literal size 2084
51:25.81 < b'LIBE1 NO AUTHENTICATE failed.'
51:25.81 NO response: b'AUTHENTICATE failed.'
I am testing with the following script:
import imaplib
import msal
app = msal.ConfidentialClientApplication(
client_id='CLIENT_ID',
authority="https://login.microsoftonline.com/TENANT_ID",
client_credential="SECRET_KEY_VALUE"
```)
result = app.acquire_token_for_client(scopes=['https://outlook.office365.com/.default'])
def generate_auth_string(user, token):
return 'user=%s\1auth=Bearer %s\1\1' % (user, token)
# IMAP time!
mailserver = 'outlook.office365.com'
imapport = 993
imap = imaplib.IMAP4_SSL(mailserver, imapport)
imap.debug = 4
imap.authenticate('XOAUTH2', lambda _: generate_auth_string('USER_EMAIL_ADDRESS', result['access_token']))
print(result)
What could be the cause? Is there perhaps some additional step that needs to be taken in the app registration web app? How can I get more informative logs of what exactly is going wrong with the authentication? I have been able to reproduce the same failure using openssl and telnet on the command line by issuing the individual imap protocol commands but this provides no additional information beyond "NO AUTHENTICATE failed".
Sign in to answer