Ошибка входа для пользователя ' '. Срок действия токена истек при использовании приложения Azure Function и Azure SQL Service с использованием управляемой идентификации - PullRequest
1 голос
/ 09 июля 2020

Я использую приложение-функцию, которое запускается служебной шиной. Он подключается к 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 Ответ

1 голос
/ 17 июля 2020

Вам нужно CREATE USER <Azure_AD_principal_name> FROM EXTERNAL PROVIDER; на Azure SQL Сервере. Вы можете увидеть официальный документ .

А еще нужно открыть Identity статус On на портале .

Мой результат.

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);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...