I am trying to create a daemon app that reads a shared mailbox. I do not directly log on to the shared mail box. The app is registered in Azure and I am getting an access token, but when I try to access the inbox, I am getting the following error.
26:14.88 < b'CKLI1 OK AUTHENTICATE completed.'
26:14.88 > b'CKLI2 SELECT inbox'
26:14.88 < b'CKLI2 BAD User is authenticated but not connected.'
My app has access to the mail box. When I run the following command, I get the access granted message like below.
Test-ApplicationAccessPolicy -Identity sharedMailboxAddress -AppId myappnum
AccessCheckResult : Granted
Here is the code.
conf = json.load(open(sys.argv1))
def generate_auth_string(user, token):
return f"user={user}\x01auth=Bearer {token}\x01\x01"
# The pattern to acquire a token looks like this.
result = None
# Firstly, looks up a token from cache
# Since we are looking for token for the current app, NOT for an end user,
# notice we give account parameter as None.
app = msal.ConfidentialClientApplication(conf['client_id'], authority=conf['authority'], client_credential=conf['secret'])
result = app.acquire_token_silent(conf['scope'], account=None)
if not result:
print("No suitable token in cache. Get new one.")
result = app.acquire_token_for_client(scopes=conf['scope'])
if "access_token" in result:
print(result['token_type'])
pprint.pprint(result)
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id"))
#IMAP AUTHENTICATE
imap = imaplib.IMAP4_SSL('outlook.office365.com', 993)
imap.debug = 4
imap.authenticate("XOAUTH2", lambda x:generate_auth_string('sharedMailboxAddress',result['access_token']))
imap.select('Inbox')
My admin also confirmed that the shared mailbox has IMAP enabled. Below is the API permission.
I am not sure if it is the code or the permission that I need to configure differently. Please help.