Login failed for user '<token-identified principal>'. Token is expired when using Azure Function app and Azure SQL Service using Managed Identity

瘦欲@ 提交于 2020-07-22 06:01:06

问题


I am using a function app which is service bus triggered. It connects to Azure SQL Server using Managed Identity.

The connection is created using the following code.

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

I get a few thousand events every day, and all these are failing on connecting to the database.

The stack trace from our logs is

[{"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"}]

Appreciate any help Thanks in advance


回答1:


You need CREATE USER <Azure_AD_principal_name> FROM EXTERNAL PROVIDER; in Azure SQL Server.You can see offical document.

And you also need to open Identity status On in portal.

My Result.

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);
        }
    }
}


来源:https://stackoverflow.com/questions/62809422/login-failed-for-user-token-identified-principal-token-is-expired-when-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!