`SimpleHttpOperator` 如何自动刷新 Microsoft Graph API 的 Token

解读

在国内企业落地 Airflow 时,常把 DAG 当作“调用 Microsoft Graph API(如 Outlook 邮件、OneDrive 文件、Azure AD 用户)”的 ETL 链路。Graph API 的 Access Token 有效期只有 60~75 分钟,而 DAG 可能跑数小时甚至跨天;如果 Token 过期,SimpleHttpOperator 会直接收到 401,任务失败。
面试想考察:

  1. 你是否知道 SimpleHttpOperator 本身不会自动刷新 Token;
  2. 能否把“获取/刷新 Token”封装成 Airflow 可复用的逻辑,并保证并发安全;
  3. 是否熟悉 Azure AD 国内版(世纪互联)与国际版的端点差异、证书/密钥两种模式、以及如何把敏感信息放进 Airflow Connections/Variables;
  4. 能否用 XCom 或自定义 Hook 把刷新动作对下游任务透明化,做到“一次刷新,全 DAG 复用”。

知识点

  • OAuth2 客户端凭证流(client_credentials) 与 授权码流(authorization_code) 在国内 Graph 场景最常用;前者适合后台服务,后者需要用户登录。
  • Token 缓存键:{tenant_id}_{client_id}_{scope_hash},防止多 DAG 并发时重复刷新。
  • Airflow 并发安全:Hook 实例在 Worker 进程内是单例,但不同 Worker 之间需用 外部缓存(Redis、Memcached) 或 Airflow Variables 的“compare-and-set”机制 避免 Race Condition。
  • SimpleHttpOperator 的 headers 参数支持 Jinja2,因此可以把 {{ task_instance.xcom_pull(task_ids='refresh_token') }} 直接写进 headers,实现“无代码侵入”地带上最新 Token。
  • 国内世纪互联 Graph 端点:https://microsoftgraph.chinacloudapi.cn,Token 端点:https://login.partner.microsoftonline.cn/{tenant}/oauth2/v2.0/token,必须显式指定,否则默认国际云会 400。
  • 密钥轮换:把 client_secret 存进 Airflow Connections 的 password 字段,利用“连接 ID 版本号”机制,可在不重启 Worker 的情况下热更新。
  • 日志脱敏:在 Hook 中重写 log.info 时,使用 mask_secret(token) 把返回的 access_token 打码,满足国内安全审计要求。

答案

步骤一:自定义 MsGraphHook(继承 HttpHook),封装“取 Token + 缓存 + 自动刷新”

class MsGraphHook(HttpHook):
    def __init__(self, azure_conn_id='azure_default', scope=None):
        super().__init__(http_conn_id=azure_conn_id)
        self.scope = scope or 'https://graph.microsoft.com/.default'
        self.cache_key = f"graph_token_{self.scope}"

    def get_token(self, context):
        # 先读缓存
        cached = Variable.get(self.cache_key, default_var=None)
        if cached:
            data = json.loads(cached)
            exp = int(data['expires_at'])
            if exp - 60 > time.time():          # 留 60 秒 buffer
                return data['access_token']

        # 缓存未命中或过期,调用 Azure AD
        conn = self.get_connection(self.http_conn_id)
        tenant = conn.extra_dejson['tenant_id']
        client_id = conn.login
        client_secret = conn.password
        token_url = f"https://login.partner.microsoftonline.cn/{tenant}/oauth2/v2.0/token"

        body = {
            'grant_type': 'client_credentials',
            'client_id': client_id,
            'client_secret': client_secret,
            'scope': self.scope
        }
        r = requests.post(token_url, data=body, timeout=30)
        r.raise_for_status()
        j = r.json()
        expires_at = int(time.time()) + int(j['expires_in'])
        Variable.set(self.cache_key,
                     json.dumps({'access_token': j['access_token'],
                                'expires_at': expires_at}),
                     serialize_json=False)
        mask_secret(j['access_token'])
        return j['access_token']

步骤二:在 DAG 里用 PythonOperator 先刷新 Token,再让下游 SimpleHttpOperator 通过 XCom 取

def refresh(**context):
    hook = MsGraphHook()
    token = hook.get_token(context)
    return token

with DAG('graph_pipeline', schedule='@hourly', catchup=False) as dag:
    t0 = PythonOperator(task_id='refresh_token', python_callable=refresh)

    t1 = SimpleHttpOperator(
        task_id='call_graph',
        method='GET',
        http_conn_id='graph_api',
        endpoint='v1.0/users',
        headers={
            "Authorization": "Bearer {{ task_instance.xcom_pull(task_ids='refresh_token') }}",
            "Content-Type": "application/json"
        },
        log_response=True
    )
    t0 >> t1

步骤三:把 tenant_id、client_id、client_secret 统一存进 Connections,ID 为 azure_default,JSON 格式 {"tenant_id": "xxx"};把 Graph 的 host microsoftgraph.chinacloudapi.cn 存为另一个 Connection graph_api,这样 SimpleHttpOperator 会自动拼接 base_url。
步骤四:若 DAG 并发量高,可把 Variable.set/compare_and_set 换成 Redis 分布式锁,保证同一秒只刷新一次。
步骤五:在 CI/CD 里定期轮换 client_secret,只需更新 Connections,DAG 零改动即可上线。

拓展思考

  1. 授权码流场景:如果 DAG 需要调用“用户级”接口(如代表用户发邮件),必须持久化 refresh_token;可把它加密后存进 Airflow Variables,并在 Hook 里实现“refresh -> access_token”的闭环,同时把刷新窗口缩短到 10 分钟,防止国内网络抖动导致 401。
  2. 证书模式:国内金融客户常禁用 client_secret,要求使用 带私钥的证书;此时 Hook 里改用 msal.ClientCredential 的 certificate 参数,并把证书文件挂载到 Worker 的 只读 Secret 卷,避免私钥落地磁盘。
  3. 多租户 SaaS:一个 Airflow 实例服务多个 Azure 租户,可在 Connection 里加字段 tenant_id,Hook 根据 dag_run.conf 动态切换租户,实现“一条 DAG,多租户复用”。
  4. 失败策略:如果刷新 Token 仍然 401,可在 SimpleHttpOperator 外加 retry_with_fresh_token 装饰器:第一次 401 时清除缓存、立即重试一次,防止偶发时钟漂移。
  5. 监控指标:在 Hook 里埋点 statsd.incr('graph_token_refresh'),通过 Grafana + Prometheus 看每小时刷新次数,若突增可能 secret 泄露或并发 Bug,方便国内运维团队及时告警。