Rust中azure_identity的ClientSecretCredential与Azure存储SDK兼容问题求助
解决Rust中Azure Identity与Storage Blobs的版本兼容问题
你的问题核心是azure_identity 0.21和azure_storage_blobs 0.14版本不兼容,两个crate在认证类型的转换逻辑上出现断层,导致From<Arc<ClientSecretCredential>> trait未实现。以下是两种可行的解决思路:
方案一:对齐crate版本
azure_storage_blobs和azure_identity同属Azure Rust SDK生态,版本需要配套使用。azure_storage_blobs 0.14对应的azure_identity应为0.14.x版本(而非0.21)。调整Cargo.toml中的依赖版本:
[dependencies] azure_storage = "0.14" azure_storage_blobs = "0.14" azure_identity = "0.14" tokio = { version = "1.0", features = ["full"] }
配套版本的实现代码如下:
use azure_identity::ClientSecretCredential; use azure_storage::authorization::StorageCredentials; use azure_storage_blobs::prelude::*; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client_id = "你的客户端ID"; let tenant_id = "你的租户ID"; let client_secret = "你的客户端密钥"; let account_name = "你的存储账户名"; let container_name = "你的容器名"; // 创建ClientSecretCredential实例 let credential = ClientSecretCredential::new( tenant_id, client_id, client_secret, None, )?; // 转换为StorageCredentials(配套版本已实现该From trait) let credentials = StorageCredentials::from(Arc::new(credential)); // 创建Blob服务客户端并列出Blob let blob_service_client = BlobServiceClient::new(account_name, credentials); let container_client = blob_service_client.container_client(container_name); let mut stream = container_client.list_blobs().into_stream(); while let Some(result) = stream.next().await { let blob = result?; println!("Blob名称: {}", blob.name); } Ok(()) }
方案二:手动实现Token认证(不依赖版本匹配)
如果不想调整版本,可以直接用ClientSecretCredential获取Blob存储的访问Token,手动构建StorageCredentials::BearerToken:
use azure_identity::ClientSecretCredential; use azure_storage::authorization::StorageCredentials; use azure_storage_blobs::prelude::*; use std::sync::Arc; use azure_core::TokenCredential; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client_id = "你的客户端ID"; let tenant_id = "你的租户ID"; let client_secret = "你的客户端密钥"; let account_name = "你的存储账户名"; let container_name = "你的容器名"; // Blob存储的固定资源标识 let blob_resource = "https://storage.azure.com/"; // 创建ClientSecretCredential实例 let credential = Arc::new(ClientSecretCredential::new( tenant_id, client_id, client_secret, None, )?); // 获取Blob存储的访问Token let token = credential.get_token(&[&format!("{}.default", blob_resource)]).await?; // 构建BearerToken类型的StorageCredentials let credentials = StorageCredentials::BearerToken(token.token.secret()); // 创建客户端并列出Blob let blob_service_client = BlobServiceClient::new(account_name, credentials); let container_client = blob_service_client.container_client(container_name); let mut stream = container_client.list_blobs().into_stream(); while let Some(result) = stream.next().await { let blob = result?; println!("Blob名称: {}", blob.name); } Ok(()) }
这种方式跳过了版本间的类型转换依赖,直接使用Token完成认证,兼容性更强。
内容的提问来源于stack exchange,提问作者nik
相关产品推荐
相关产品推荐

