You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python对接Microsoft Graph的一次性自动认证?

问题

从微软开发者页面下载的Python对接Microsoft Graph API脚本可正常运行,但每次启动都需手动通过设备码认证(控制台提示打开指定链接输入验证码完成认证)。当前认证逻辑使用DeviceCodeCredential实现,配置文件已包含clientId、clientSecret、tenantId等Azure凭据,希望实现仅一次认证,后续启动无需手动操作。

当前认证函数代码:

def initialize_graph_for_user_auth(config):
    this.settings = config
    client_id = this.settings['clientId']
    tenant_id = this.settings['authTenant']
    graph_scopes = this.settings['graphUserScopes'].split(' ')

    this.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id)
    this.user_client = GraphClient(credential=this.device_code_credential, scopes=graph_scopes)

配置文件内容:

[azure]
clientId = <CLIENT_ID>
clientSecret = <CLIENT_SECRET>
tenantId = <TENANT_ID>
authTenant = common
graphUserScopes = GroupMember.ReadWrite.All
解决方案

要实现一次认证后自动复用凭据,可通过持久化Token缓存来实现,具体步骤如下:

  1. 导入PersistentTokenCache
    从azure.identity库中引入PersistentTokenCache类,用于将认证令牌存储到本地文件。

  2. 修改认证函数,添加持久化缓存配置
    创建PersistentTokenCache实例并指定缓存文件路径,将其传入DeviceCodeCredential的参数中,修改后的代码如下:

    from azure.identity import DeviceCodeCredential, PersistentTokenCache
    
    def initialize_graph_for_user_auth(config):
        this.settings = config
        client_id = this.settings['clientId']
        tenant_id = this.settings['authTenant']
        graph_scopes = this.settings['graphUserScopes'].split(' ')
    
        # 初始化持久化Token缓存,指定存储文件路径
        token_cache = PersistentTokenCache(file_path="./graph_token_cache.json")
        this.device_code_credential = DeviceCodeCredential(
            client_id,
            tenant_id=tenant_id,
            token_cache=token_cache
        )
        this.user_client = GraphClient(credential=this.device_code_credential, scopes=graph_scopes)
    
  3. 运行验证

    • 第一次运行脚本时,仍需手动完成设备码认证;
    • 认证完成后,令牌会自动保存到指定的本地缓存文件中;
    • 后续启动脚本时,DeviceCodeCredential会自动读取缓存中的令牌,无需再次手动认证。

注意事项

  • 确保缓存文件所在目录有读写权限;
  • 若缓存中的令牌过期(或刷新令牌失效),可能需要重新进行一次手动认证;
  • 配置文件中的clientSecret在当前用户认证场景下暂未用到,若需切换为服务主体认证(无用户交互),可改用ClientCredential类实现。

内容的提问来源于stack exchange,提问作者Mark Baumann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 08:23:25