如何在Ruby on Rails中使用Azure Managed Identity访问Azure Cosmos DB for MongoDB
使用Azure托管身份认证Ruby on Rails + Mongoid连接Azure Cosmos DB for MongoDB
核心逻辑说明
Azure Cosmos DB for MongoDB API支持通过Azure托管身份获取临时访问令牌,以令牌作为密码、Cosmos DB账户名作为用户名,结合SCRAM认证机制完成身份验证,无需硬编码持久化的用户名密码。
步骤1:配置Azure资源权限
给应用运行环境(如Azure App Service、VM)的托管身份(系统分配/用户分配均可)添加Cosmos DB的RBAC权限,推荐使用MongoDB Account Reader Writer(最小权限原则),确保身份具备目标数据库的读写访问权限。
步骤2:添加令牌获取依赖
在Rails项目的Gemfile中添加Azure身份认证Gem:
gem 'azure_identity'
执行bundle install完成安装。
步骤3:编写令牌获取工具类
创建app/services/azure_cosmos_token_service.rb,用于获取并缓存Azure AD访问令牌:
require 'azure_identity' require 'active_support/cache' class AzureCosmosTokenService COSMOS_RESOURCE_URI = 'https://cosmos.azure.com/' CACHE_KEY = 'cosmos_db_access_token' # 提前30分钟刷新令牌,避免过期失效 CACHE_EXPIRY = 30.minutes def self.get_token cache = ActiveSupport::Cache::RedisCacheStore.new(url: ENV['REDIS_URL']) # 生产环境用Redis缓存,开发可替换为MemoryStore cached_token = cache.read(CACHE_KEY) return cached_token if cached_token.present? # 若使用用户分配的托管身份,需添加client_id参数:client_id: '你的身份Client ID' credential = Azure::Identity::ManagedIdentityCredential.new token_response = credential.get_token(COSMOS_RESOURCE_URI) token = token_response.token cache.write(CACHE_KEY, token, expires_in: CACHE_EXPIRY) token end end
步骤4:修改Mongoid配置
更新config/mongoid.yml,替换原用户名密码配置:
production: clients: default: database: <你的数据库名称> hosts: - <你的Cosmos账户名>.mongo.cosmos.azure.com:10255 options: user: <你的Cosmos账户名> password: <%= AzureCosmosTokenService.get_token %> ssl: true auth_source: admin auth_mechanism: :scram
步骤5:验证与排障
- 启动Rails应用,执行数据库查询操作(如
Model.all)验证连接是否成功。 - 若遇权限错误:检查RBAC角色是否正确分配,等待权限生效(通常需5-10分钟)。
- 若遇令牌获取失败:确认应用运行环境已启用托管身份,且网络可访问Azure AD端点。
内容的提问来源于stack exchange,提问作者Vansh
相关产品推荐
相关产品推荐

