msal生成令牌请求Outlook日历时偶发InvalidAuthenticationToken错误排查
排查MSAL令牌请求Outlook日历时的InvalidAuthenticationToken问题
问题概述
开发的Python程序通过MSAL和requests库读取Outlook日历,仅一名测试用户频繁触发InvalidAuthenticationToken错误(提示令牌过期或无效),其余用户无此问题。错误非每次触发,程序重启后仍存在,日志显示令牌处于有效期内。
代码实现
import msal import requests class OutlookClient(): def __init__(self, client_id, authority): # client_id和authority是Azure注册应用的UUID格式ID self.app = msal.PublicClientApplication( client_id = client_id, client_credential = None, authority = msal.authority.AuthorityBuilder(msal.authority.AZURE_PUBLIC,authority) ) def getToken(self, username, pw): # 认证访问员工日历的测试员工凭据 self.auth = self.app.acquire_token_by_username_password(username,pw, scopes=["Calendars.Read","Calendars.Read.Shared","People.Read"] ) return def getCalendar(self, agentCal, startDate, endDate): # agentCal为目标员工ID graph_data = None if 'access_token' in self.auth: req = "https://graph.microsoft.com/v1.0/users/"+agentCal+"/calendar/calendarView"+\ "?startDateTime="+ startDate.strftime("%Y-%m-%dT02:00")+\ "&endDateTime="+ endDate.strftime("%Y-%m-%dT23:00") graph_data = requests.get(req, headers={'Authorization': 'Bearer ' + self.auth['access_token'], 'content-type': 'application/json'} ).json() try: return graph_data['value'] except KeyError: return []
错误信息
graph_data = {'error': {'code': 'InvalidAuthenticationToken', 'message': 'Access token has expired or is not yet valid.', 'innerError': {'date': '2022-10-27T05:56:39', 'request-id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'client-request-id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' } } }
正常令牌日志
self.auth = {'token_type': 'Bearer', 'scope': 'Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Mail.ReadWrite Mail.Send openid People.Read profile User.Read email', 'expires_in': 4581, 'ext_expires_in': 4581, 'access_token': 'eyJ0eXAiOiJKV1Q...', 'refresh_token': '0.AREA...', 'id_token': 'eyJ0eXAiOiJKV1Q...', 'client_info': 'eyJ1aWQ...', 'id_token_claims': {...} }
排查方向
- 时间同步问题:检查该用户设备的系统时间是否与Azure AD服务器时间偏差过大(超过5分钟),令牌有效期校验依赖时间同步,偏差可能导致服务器判定令牌过期。
- 令牌复用与刷新逻辑缺失:当前代码获取令牌后未处理过期自动刷新,若同一令牌被多次复用,可能在有效期快结束时因网络延迟等问题触发错误。需添加令牌过期检查,在
expires_in接近阈值时调用acquire_token_by_refresh_token刷新令牌。 - 用户账号特殊状态:确认该用户账号是否存在异常,比如多重身份验证设置变更、权限被临时调整、账号在其他设备登录导致令牌失效,或者Azure AD中该账号的令牌策略与其他用户不同。
- 网络环境差异:该用户可能处于代理网络或防火墙环境下,请求过程中令牌被篡改或丢失部分内容,可让用户测试在其他网络环境下是否复现问题。
- 令牌受众与权限匹配:解析该用户的access_token,确认
aud(受众)是否为https://graph.microsoft.com,scp(权限)是否包含Calendars.Read等必要权限,是否存在权限范围不一致的情况。 - 请求URL参数问题:检查请求中的
agentCal是否正确,是否存在该用户访问其他员工日历时权限不足的情况(虽然错误提示是令牌问题,但权限不足可能有误导性提示)。
内容的提问来源于stack exchange,提问作者ElDimano
相关产品推荐
相关产品推荐

