使用 App Service 和 Azure SQL 的用户分配身份是否有效?

User Assigned Identities with App Service and Azure SQL does that work?

我正在尝试让应用服务连接到 Azure Sql 数据库。我可以 git 使用相同的代码很好地使用系统分配的身份,但我更喜欢使用用户分配的身份 (UAI),但我无法让它工作。

我做的步骤:

  1. 通过门户创建了一个 UAI,UAI 的名称"uai-dev-appname-001"
  2. 在 Azure 应用服务的身份选项卡中,我选择了 'User Assigned Identity' 并选择了上一步中制作的 UAI。
  3. 运行以下SQLCMD
CREATE USER [uai-dev-appname-001] FROM EXTERNAL PROVIDER
ALTER ROLE db_datareader ADD MEMBER [uai-dev-appname-001]
ALTER ROLE db_datawriter ADD MEMBER [uai-dev-appname-001]
  1. 将 ASP.NET 中的连接字符串设置为:

    Data Source=sqlsrv-name-dev-001.database.windows.net; Initial Catalog=sqldb-name-dev-001;

  2. 在我的ASP.NET核心中使用以下代码:
SqlConnection connection = new SqlConnection
{
   ConnectionString = configuration.GetConnectionString("nameDatabase")
};
AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
var token = provider.GetAccessTokenAsync("https://database.windows.net/").Result;
connection.AccessToken = token;
  1. 部署到 Azure 应用服务并观看 URL。结果是:错误500.30
  2. 查看应用程序事件日志:

    Unhandled exception. System.AggregateException: One or more errors occurred. (Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried the following 3 methods to get an access token, but none of them worked. Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Received a non-retryable error. MSI ResponseCode: BadRequest, Response: {"StatusCode":400,"Message":"No MSI found for specified ClientId/ResourceId.","CorrelationId":"a68bf757-518a-42e1-85a9-342320d39b5a"} Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "D:\local\LocalAppData.IdentityService\AzureServiceAuth\tokenprovider.json" Parameters: Connection String: [No connection string specified], Resource: https://database.windows.net, Authority: . Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command, operable program or batch file.

IMO 中最有趣的部分是:

Response: {"StatusCode":400,"Message":"No MSI found for specified ClientId/ResourceId.","CorrelationId":"a68bf757-518a-42e1-85a9-342320d39b5a"}

我的问题是:

Microsoft.Azure.Services.AppAuthentication 的 1.2.1 版支持用户分配的托管身份。

所以,请将Microsoft.Azure.Services.AppAuthentication的版本更新到最新版本。

然后在AppService的Appsettings中设置AzureServicesAuthConnectionStringRunAs=App;AppId={ClientId of user-assigned identity}

例如

RunAs=App;AppId=587f16c8-81ed-41c7-b19a-9ded0dbe2ca2

可以找到文档 here

完成这些步骤后,您的代码应该使用用户分配的托管标识。