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

如何在Apache Spark中使用PEM证书访问ADLS Gen2

在Apache Spark中使用证书认证的Azure SPN访问ADLS Gen2

问题背景

我有一个Azure服务主体(SPN),可通过PEM证书读取ADLS Gen2中的数据。使用Azure SDK时,能通过CertificateCredential轻松实现认证并访问存储,但在Apache Spark中找不到对应的配置方式——ABFS官方文档里的认证方案没有直接支持证书认证的SPN,希望能像配置客户端密钥那样,通过Spark配置完成证书认证。

Azure SDK中的实现示例:

from azure.identity import CertificateCredential

azure_credential = CertificateCredential(
                tenant_id=tenant_id,
                client_id=client_id,
                certificate_data=client_certificate_bytes
            )
DataLakeServiceClient(
        account_url=ACCOUNT_URL,
        credential=azure_credential,
    ).get_file_system_client(blob_container_name)

解决方案

Spark的ABFS原生不直接支持证书认证SPN,但可以通过预获取访问令牌的方式实现,步骤如下:

1. 使用Azure SDK获取ADLS Gen2访问令牌

先通过证书凭据向Azure AD请求存储服务的访问令牌:

from azure.identity import CertificateCredential

tenant_id = "你的租户ID"
client_id = "你的SPN客户端ID"
cert_path = "本地PEM证书路径"

# 读取证书二进制数据
with open(cert_path, "rb") as cert_file:
    cert_data = cert_file.read()

# 创建证书凭据并获取令牌
credential = CertificateCredential(tenant_id, client_id, certificate_data=cert_data)
# 存储服务的资源标识符为https://storage.azure.com/
token = credential.get_token("https://storage.azure.com/.default")
access_token = token.token

2. 在Spark中配置使用令牌

将获取到的访问令牌配置到Spark会话中,即可通过ABFS访问ADLS Gen2:

spark_session.conf.set("fs.azure.account.auth.type", "OAuth")
spark_session.conf.set("fs.azure.account.oauth.provider.type", "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider")
spark_session.conf.set("fs.azure.account.oauth2.access.token", access_token)
spark_session.conf.set("fs.azure.account.oauth2.client.id", client_id)

注意事项

  • Azure AD颁发的访问令牌默认有效期为1小时,需要定时刷新令牌并更新Spark配置,避免访问失败。
  • 若需要长期自动化运维,可考虑自定义TokenProvider(基于Java开发),实现证书自动刷新令牌的逻辑,但开发复杂度较高。

内容的提问来源于stack exchange,提问作者Behroz Sikander

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:11:16