Visual Studio 使用用户管理的标识将C# Azure函数与Azure SQL连接,身份验证失败

r7s23pms  于 2022-11-17  发布在  C#
关注(0)|答案(1)|浏览(159)

我当前正在使用Azure函数和Azure SQL连接。Azure SQL Server是使用用户托管标识Map的。当我使用C#中的Azure函数连接Azure SQL Server时,我遇到身份验证问题。请在下面查找问题。

"Microsoft.Data.SqlClient.SqlException (0x80131904): ManagedIdentityCredential authentication failed: Service request failed.\r\nStatus: 400 (Bad Request)\r\n\r\nContent:\r\n\r\n\r\nHeaders:\r\nDate: Thu, 10 Nov 2022 11:59:51 GMT\r\nServer: Kestrel\r\nTransfer-Encoding: chunked\r\nX-CORRELATION-ID: REDACTED\r\nContent-Type: application/json; charset=utf-8\r\n\nSee the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot\r\n ---> Azure.Identity.AuthenticationFailedException: ManagedIdentityCredential authentication failed: Service request failed.\r\nStatus: 400 (Bad Request)\r\n\r\nContent:\r\n\r\n\r\nHeaders:\r\nDate: Thu, 10 Nov 2022 11:59:51 GMT\r\nServer: Kestrel\r\nTransfer-Encoding: chunked\r\nX-CORRELATION-ID: REDACTED\r\nContent-Type: application/json; charset=utf-8\r\n\nSee the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot\r\n ---> Azure.RequestFailedException: Service request failed.\r\nStatus: 400 (Bad Request)\r\n\r\nContent:\r\n\r\n\r\nHeaders:\r\nDate: Thu, 10 Nov 2022 11:59:51 GMT\r\nServer: Kestrel\r\nTransfer-Encoding: chunked\r\nX-CORRELATION-ID: REDACTED\r\nContent-Type: application/json; charset=utf-8\r\n\r\n   at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean async, TokenRequestContext context, Response response, CancellationToken cancellationToken)\r\n   at Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)\r\n   at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)\r\n   at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)\r\n   --- End of inner exception stack trace ---\r\n   at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage)\r\n   at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)\r\n   at Azure.Identity.ManagedIdentityCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)\r\n   at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenAsync(SqlAuthenticationParameters parameters)\r\n   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass147_1.<<GetFedAuthToken>b__1>d.MoveNext()\r\n--- End of stack trace from previous location ---\r\n   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)\r\n   at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)\r\n   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\r\n   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)\r\n   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)\r\n   at SampleFunction.Repository.TaskRepository.GetData() in C:\\Users\\vinothkumar.sivaram\\Downloads\\SampleFunction12\\SampleFunction\\SampleFunction\\Repository\\TaskRepository.cs:line 38\r\nClientConnectionId:bc712cd9-cff0-4296-b273-3253088258cd",

请找到我的示例代码

函数

[FunctionName("GetItems")]
        public async Task<IActionResult> GetItems(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            var TaskData = _repository.GetData();
                       
            return new OkObjectResult(TaskData);
        }

SQL帮助器类

public async Task<List<TaskModel>> GetData()
        {
            List<TaskModel> taskList = new List<TaskModel>();

                using (SqlConnection connection = new SqlConnection(Environment.GetEnvironmentVariable("SqlConnectionString")))
                {

                connection.Open();
                {
                    //
                }

                }

            return taskList;
        }

连接字符串

“SqlConnection字符串”:“服务器=tcp:dbserver.database.windows.net,1433;初始目录=db;身份验证= Active Directory管理的标识;
请查找Azure身份验证的步骤

此外,我还为我的用户ID分配了角色和访问控制。
但我仍然面临ManagedIdentity身份验证问题。
特别是我不想使用Azure密钥库。需要在连接字符串中使用托管身份和Active Directory托管身份

k5ifujac

k5ifujac1#

使用用户管理的标识将C# Azure函数与Azure SQL连接。身份验证失败
通常,连接字符串会根据身份验证的类型而变化,其中用户ID和身份验证值也会变化。

@Scott Mildenberger建议MS Doc在指定应用程序配置设置时,在数据库服务器的连接字符串中添加属性User Id=ClientIdOfManagedIdentity
在您的情况下,AuthenticationUserId值也设置为Active Directory Managed IdentityClientIdOfManagedIdentity,然后必须部署它以反映更改和工作。

相关问题