Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ef code first MSI能否先使用EF CodeFirst?_Ef Code First_Entity Framework Migrations_Azure Managed Identity - Fatal编程技术网

Ef code first MSI能否先使用EF CodeFirst?

Ef code first MSI能否先使用EF CodeFirst?,ef-code-first,entity-framework-migrations,azure-managed-identity,Ef Code First,Entity Framework Migrations,Azure Managed Identity,我已经在这个问题上纠缠了很长一段时间了,我自己也没什么进展 我正在尝试使用MSI令牌从Azure应用程序服务连接到EF CodeFirst托管数据库 当我使用ARM部署应用程序服务时,我生成了一个输出,确保它创建了一个服务主体: { "principalId":"98f2c1f2-0a86-4ff1-92db-d43ec0edxxxx"," tenantId":"e6d2d4cc-b762-486e-8894-4f5f440dxxxx", "type":"SystemAssigne

我已经在这个问题上纠缠了很长一段时间了,我自己也没什么进展

我正在尝试使用MSI令牌从Azure应用程序服务连接到EF CodeFirst托管数据库

当我使用ARM部署应用程序服务时,我生成了一个输出,确保它创建了一个服务主体:

 {
  "principalId":"98f2c1f2-0a86-4ff1-92db-d43ec0edxxxx","
  tenantId":"e6d2d4cc-b762-486e-8894-4f5f440dxxxx",
  "type":"SystemAssigned"
 }
在Kudu中,环境变量显示正在安装:

MSI_ENDPOINT = http://127.0.0.1:41239/MSI/token/
MSI_SECRET = 7C1B16Fxxxxxxxxxxxxx
我在Azure门户中提供了一个连接字符串,如下所示:

Data Source=nzmoebase0000bt.database.windows.net;Initial Catalog=nzmoebase0001bt;Connect Timeout=300;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=300;
我已将主体作为所有者添加到数据库中

Note: I cannot do the same for the master db.
将令牌添加到DbContext中,如下所示:

Data Source=nzmoebase0000bt.database.windows.net;Initial Catalog=nzmoebase0001bt;Connect Timeout=300;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=300;
正在使用以下方法添加令牌:

    static async Task AttachAccessTokenToDbConnection(IDbConnection dbConnection)
    {
        SqlConnection sqlConnection = dbConnection as SqlConnection;
        if (sqlConnection == null)
        {
            return;
        }
        string msiEndpoint = Environment.GetEnvironmentVariable("MSI_ENDPOINT");
        if (string.IsNullOrEmpty(msiEndpoint))
        {
            return;
        }

        var msiSecret = Environment.GetEnvironmentVariable("MSI_SECRET");
        if (string.IsNullOrEmpty(msiSecret))
        {
            return;
        }

        // To get around:
        // "Cannot set the AccessToken property if 'UserID', 'UID', 'Password', or 'PWD' has been specified in connection string."
        var terms = new[] {"UserID","Password","PWD=","UID=" };
        string connectionString = dbConnection.ConnectionString;

        foreach (var term in terms)
        {
            if (connectionString.Contains(term, StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }
        }

        string accessToken = await AppCoreDbContextMSITokenFactory.GetAzureSqlResourceTokenAsync();
        sqlConnection.AccessToken = accessToken;
    }
启用跟踪后,令牌为:

 .eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI....
使用jwt.io解码的结果给出:

{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "FSimuFrFNoC0sJXGmv13nNZceDc",
  "kid": "FSimuFrFNoC0sJXGmv13nNZceDc"
}.{
  "aud": "https://database.windows.net/",
  "iss": "https://sts.windows.net/e6d2d4cc-b762-486e-8894-4f5f440dxxxx/",
  "iat": 1522783025,
  "nbf": 1522783025,
  "exp": 1522786925,
  "aio": "Y2NgYPjNdyJd9zrzpLavJSEzNIuPAAA=",
  "appid": "d1057cea-461b-4946-89a9-d76439c2xxxx",
  "appidacr": "2",
  "e_exp": 262800,
  "idp": "https://sts.windows.net/e6d2d4cc-b762-486e-8894-4f5f440dxxxx/",
  "oid": "98f2c1f2-0a86-4ff1-92db-d43ec0edxxxx",
  "sub": "98f2c1f2-0a86-4ff1-92db-d43ec0edxxxx",
  "tid": "e6d2d4cc-b762-486e-8894-4f5f440dxxxx",
  "uti": "59bqKWiSL0Gf0bTCI0AAAA",
  "ver": "1.0"
}.[Signature]
我根据网上的几条建议添加了
persistensecurityinfo=True
,但没有发现任何问题

Data Source=nzmoebase0000bt.database.windows.net;Initial Catalog=nzmoebase0001bt;MultipleActiveResultSets=False;Persist Security Info = True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
我得到的错误是:

[InvalidOperationException: This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened connection.]
是否有人使用CodeFirst、迁移和MSI连接到数据库?在这一点上,在经历了几个星期的困境之后,我开始怀疑这是否可能


感谢您的帮助,即使只是证明它可以工作,对于初学者来说

不幸的是,据我所知,没有。这是一个项目的主要绊脚石,它不得不退回到不安全的用户名/密码加载的连接字符串。

您可以在sql连接上设置如下访问令牌:

public class MyDatabaseContext : DbContext
{
    public MyDatabaseContext(DbContextOptions<MyDatabaseContext> options)
        : base(options)
    {
        // Get the db connection
        var connection = (SqlConnection)Database.GetDbConnection();

        // Add the access token
        connection.AccessToken = new AzureServiceTokenProvider()
            .GetAccessTokenAsync("https://database.windows.net/")
            .ConfigureAwait(false).GetAwaiter().GetResult();
    }

    public DbSet<MyTable> MyTable { get; set; }
}
  • 安装
    Microsoft.Azure.Services.AppAuthentication
    nuget软件包
  • 按如下方式设置上下文类:

    public class MyDatabaseContext : DbContext
    {
        public MyDatabaseContext(DbContextOptions<MyDatabaseContext> options)
            : base(options)
        {
            // Get the db connection
            var connection = (SqlConnection)Database.GetDbConnection();
    
            // Add the access token
            connection.AccessToken = new AzureServiceTokenProvider()
                .GetAccessTokenAsync("https://database.windows.net/")
                .ConfigureAwait(false).GetAwaiter().GetResult();
        }
    
        public DbSet<MyTable> MyTable { get; set; }
    }
    
    公共类MyDatabaseContext:DbContext { 公共MyDatabaseContext(DbContextOptions选项) :基本(选项) { //获取数据库连接 var connection=(SqlConnection)Database.GetDbConnection(); //添加访问令牌 connection.AccessToken=新AzureServiceTokenProvider() .GetAccessTokenAsync(“https://database.windows.net/") .ConfigureAwait(false).GetAwaiter().GetResult(); } 公共DbSet MyTable{get;set;} }

  • 有人回答了吗?我的一位同事也遇到了同样的问题。有人能找到解决办法吗?我碰到了这个。。。。