用户“ <令牌标识的主体>”的登录失败。使用Azure Function应用和使用托管身份的Azure SQL服务时令牌已过期

时间:2020-07-09 07:17:00

标签: c# azure-function-app azure-sql-server azure-managed-identity

我正在使用由服务总线触发的功能应用程序。它使用Azure SQL Server连接到Managed Identity

使用以下代码创建连接。

new SqlConnection(this.ConnectionString)
        {
            // AzureServiceTokenProvider handles caching the token and refreshing it before it expires
            AccessToken = new AzureServiceTokenProvider().GetAccessTokenAsync("https://database.windows.net/").Result
        };

我每天都会收到几千个事件,而所有这些都无法连接到数据库。

我们日志中的堆栈跟踪为

[{"parsedStack":[{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.SqlClient.SqlInternalConnectionTds..ctor","level":0,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.SqlClient.SqlConnectionFactory.CreateConnection","level":1,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection","level":2,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionPool.CreateObject","level":3,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionPool.UserCreateRequest","level":4,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionPool.TryGetConnection","level":5,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionPool.TryGetConnection","level":6,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionFactory.TryGetConnection","level":7,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal","level":8,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection","level":9,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.SqlClient.SqlConnection.TryOpen","level":10,"line":0},
{"assembly":"System.Data.SqlClient, Version=4.5.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Data.SqlClient.SqlConnection.Open","level":11,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore.Relational, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection","level":12,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore.Relational, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open","level":13,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore.Relational, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1+Enumerator.BufferlessMoveNext","level":14,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore.SqlServer, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute","level":15,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore.Relational, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1+Enumerator.MoveNext","level":16,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+<_TrackEntities>d__17`2.MoveNext","level":17,"line":0},
{"assembly":"Microsoft.EntityFrameworkCore, Version=2.2.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","method":"Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor`1+EnumeratorExceptionInterceptor.MoveNext","level":18,"line":0},
{"assembly":"System.Linq, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Linq.Enumerable+SelectEnumerableIterator`2.MoveNext","level":19,"line":0},
{"assembly":"System.Linq, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a","method":"System.Linq.Enumerable.TryGetFirst","level":20,"line":0},
{"assembly":"MaskedProjectPNameIngestor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","method":"MaskedProjectPNameIngestor.SRFunction.RetrieveCodeAsync","level":21,"line":182,"fileName":"D:\\a\\1\\s\\MaskedProject\\PNameIngestion\\MaskedProjectPNameIngestor\\SRFunction.cs"},
{"assembly":"MaskedProjectPNameIngestor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","method":"MaskedProjectPNameIngestor.SRFunction+<Run>d__5.MoveNext","level":22,"line":121,"fileName":"D:\\a\\1\\s\\MaskedProject\\PNameIngestion\\MaskedProjectPNameIngestor\\SRFunction.cs"}],
"outerId":"0","message":"Login failed for user '<token-identified principal>'. Token is expired.","type":"System.Data.SqlClient.SqlException","id":"64152618"}]

感谢任何帮助 预先感谢

1 个答案:

答案 0 :(得分:1)

您需要在Azure SQL Server中使用CREATE USER <Azure_AD_principal_name> FROM EXTERNAL PROVIDER;。您可以看到offical document

您还需要在门户网站中打开Identity状态On

我的结果。

enter image description here

enter image description here

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Data.SqlClient;
using Microsoft.Azure.Services.AppAuthentication;
using System.Diagnostics;

namespace func_sqlcon
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
        {
            var str = "Server=tcp:*********.database.windows.net,1433;Initial Catalog=********;Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
            //Environment.GetEnvironmentVariable("sqldb_connection");
            string AccessToken;
            SqlConnection connection = new SqlConnection(str);
            try
            {
                AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/", "e4c9ab4e-bd27-40d5-8459-230ba2a757fb");
                connection.AccessToken = AccessToken;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw;
            }
            connection.Open();
            return new OkObjectResult(AccessToken);
        }
    }
}