如何在Office365中动态获取AccessToken?
动态获取Office 365 Outlook API AccessToken方案
授权码流(适合需用户交互的场景)
该方案适用于有前端界面、需要用户登录授权的应用,支持通过RefreshToken自动刷新AccessToken。
实现步骤
- 在Azure AD中注册应用,配置重定向URI,添加
Mail.Read委派权限并完成用户授权 - 引导用户访问授权URL获取授权码:
https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize? client_id={client-id} &response_type=code &redirect_uri={redirect-uri} &response_mode=query &scope=Mail.Read offline_access &state=12345
- 使用授权码交换AccessToken与RefreshToken:
import requests token_url = "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token" payload = { "client_id": "{client-id}", "client_secret": "{client-secret}", "code": "{authorization-code}", "redirect_uri": "{redirect-uri}", "grant_type": "authorization_code", "scope": "Mail.Read offline_access" } response = requests.post(token_url, data=payload) token_data = response.json() # 安全存储access_token、refresh_token及过期时间
- AccessToken过期时,用RefreshToken刷新获取新凭证:
refresh_payload = { "client_id": "{client-id}", "client_secret": "{client-secret}", "refresh_token": "{saved-refresh-token}", "grant_type": "refresh_token", "scope": "Mail.Read offline_access" } refresh_response = requests.post(token_url, data=refresh_payload) new_token_data = refresh_response.json() # 更新存储的access_token与refresh_token
客户端凭据流(适合无用户交互的后台服务)
该方案适用于后台定时任务等无需用户参与的场景,直接通过应用凭证获取AccessToken,过期后重新请求即可。
实现步骤
- 在Azure AD中注册应用,添加
Mail.Read应用权限并获取管理员同意 - 直接调用token接口获取AccessToken:
import requests token_url = "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token" payload = { "client_id": "{client-id}", "client_secret": "{client-secret}", "grant_type": "client_credentials", "scope": "https://graph.microsoft.com/.default" } response = requests.post(token_url, data=payload) token_data = response.json() access_token = token_data["access_token"] # 调用API时需指定用户ID,示例:GET https://graph.microsoft.com/v1.0/users/{user-id}/messages
注意事项
- 权限选择:根据业务场景选择委派权限(需用户授权)或应用权限(后台服务),确保权限已完成同意流程
- 安全存储:AccessToken、RefreshToken需加密存储,避免明文泄露
- 过期预判:调用API前检查AccessToken剩余有效期,提前5分钟触发刷新或重新获取逻辑
内容的提问来源于stack exchange,提问作者Ishi Silva
相关产品推荐
相关产品推荐

