在Python中使用MSAL进行OAUTH2身份验证和acquire_token_for_client会在执行之间挂起

raogr8fs  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(170)

我有一个程序来生成电子邮件在一个邮箱的草稿文件夹.最近我增强了它使用微软的OAUTH2身份验证的IMAP.遵循这个建议Sardar Agabejli和它的工作以及-
Office 365 IMAP authentication via OAuth2 and python MSAL library
我的程序批量生成大量邮件。现在我观察到,在生成一些邮件后,我的程序永远挂起等待令牌。它挂起在这一步-
result = app.acquire_token_for_client(scopes=conf['scope'])
下面是参考代码:

import imaplib
import msal
import pprint

conf = {
    "authority": "https://login.microsoftonline.com/XXXXyourtenantIDXXXXX",
    "client_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXX", #AppID
    "scope": ['https://outlook.office365.com/.default'],
    "secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", #Key-Value
    "secret-id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", #Key-ID
}
    
def generate_auth_string(user, token):
    return f"user={user}\x01auth=Bearer {token}\x01\x01"    

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'])
        
    imap = imaplib.IMAP4('outlook.office365.com')
    imap.starttls()
    imap.authenticate("XOAUTH2", lambda x: generate_auth_string("target_mailbox@example.com", result['access_token']).encode("utf-8"))

有没有人遇到过这种情况,并找到了根本原因?
我读过一些博客/论坛,指出防火墙的问题,但答案不清楚,不能理解为什么防火墙将允许前几个邮件,然后块。

mnowg1ta

mnowg1ta1#

首先使用result = app.acquire_token_for_client(scopes=conf['scope'])而不是result = app.acquire_token_silent(conf['scope'], account=None)更好。acquire_token_for_client提供的access_token保持活动的时间更长,可以说基于我的测试。

import imaplib
import msal
import pprint

conf = {
"authority": "https://login.microsoftonline.com/XXXXyourtenantIDXXXXX",
"client_id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXX", #AppID
"scope": ['https://outlook.office365.com/.default'],
"secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", #Key-Value
"secret-id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", #Key-ID
}

def generate_auth_string(user, token):
    return f"user={user}\x01auth=Bearer {token}\x01\x01"    

app = msal.ConfidentialClientApplication(conf['client_id'],
authority=conf['authority'],
client_credential=conf['secret'])

result = app.acquire_token_for_client(scopes=conf['scope'])
    
imap = imaplib.IMAP4('outlook.office365.com')
imap.starttls()
imap.authenticate("XOAUTH2", lambda x: generate_auth_string("target_mailbox@example.com", result['access_token']).encode("utf-8"))

相关问题