Azure Web应用程序找不到连接字符串

时间:2019-08-11 13:39:02

标签: asp.net azure azure-active-directory azure-web-app-service

我只是想将我的应用程序发布为Web应用程序在Azure中。我一直在面对有关连接字符串的问题。如下面的错误所示,服务器只是无法识别连接字符串是什么

Unhandled Exception: Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException: Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/b99992c6-d6c5-4028-99b5-a1f106bb90bc. Exception Message: Tried the following 3 methods to get an access token, but none of them worked.
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/b99992c6-d6c5-4028-99b5-a1f106bb90bc. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An attempt was made to access a socket in a way forbidden by its access permissions
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/b99992c6-d6c5-4028-99b5-a1f106bb90bc. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Visual Studio Token provider file not found at "D:\local\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json"
Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/b99992c6-d6c5-4028-99b5-a1f106bb90bc. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command,
operable program or batch file.

   at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.GetAuthResultAsyncImpl(String authority, String resource, String scope, CancellationToken cancellationToken)
   at Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider.<get_KeyVaultTokenCallback>b__8_0(String authority, String resource, String scope)
   at Microsoft.Azure.KeyVault.KeyVaultCredential.PostAuthenticate(HttpResponseMessage response)
   at Microsoft.Azure.KeyVault.KeyVaultCredential.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(String vaultBaseUrl, Nullable`1 maxresults, Dictionary`2 customHeaders, CancellationToken cancellationToken)
   at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, String vaultBaseUrl, Nullable`1 maxresults, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
   at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Synergy.Program.Main(String[] args) in C:\Users\Erkan Er\source\repos\Synergy\Program.cs:line 21

下面是appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=server.database.windows.net;Initial Catalog=synergylearn_db;User ID=userid;Password=password;Connect Timeout=60;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;RunAs=App;",
    "AzureStorageConnectionString-1": "DefaultEndpointsProtocol=https;AccountName=encamina;AccountKey=V0/+NhCGcq1vBCc1wJ5L9V620fi5E0cX0cX4/pbOFzjqBxRapLBmaDt75LQcoX3HBskY/34E0MwGH/OWToryUg==;EndpointSuffix=core.windows.net"
  },
  "AppSettings": {
    "Secret": "abc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Authentication": {
    "Google": {
      "ClientId": "xxx",
      "ClientSecret": "xx"
    }
  }
}

还有Startup.cs

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            }); ;


        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        });

        services.AddDbContext<SynergyDbContext>( 
           options => options.UseSqlServer(
               Configuration.GetConnectionString("DefaultConnection")
               //Configuration["ConnectionStrings:DefaultConnection"]
               )
           );
        services.AddTransient<SynergyDbContext>();

如果我使用相同的设置从本地计算机运行它,则可以正常运行。但是,它在服务器上不起作用。有什么想法吗?

更新

何时,我从网址https://myapp.scm.azurewebsites.net/env进行检查,看到以下部分:

Connection Strings
LocalSqlServer
ConnectionString = data source=.\SQLEXPRESS;Integrated 
Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
ProviderName = System.Data.SqlClient

此外,在此部分中,还会显示正确的连接字符串:

SQLCONNSTR_DefaultConnection = Data Source=server.database.windows.net;Initial Catalog=synergylearn_db;User ID=userid;Password=password;Connect Timeout=60;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;RunAs=App;

3 个答案:

答案 0 :(得分:5)

对我来说,这是在本地运行功能应用程序并更改Microsoft密码时发生的, 由于登录的用户凭据用于授权受管身份, 尝试重新输入您的凭据

答案 1 :(得分:2)

我知道这有一个公认的答案,但它对我的密钥库问题没有太大帮助,它有相同的错误消息,所以在这里发布一个新答案,以防万一它有助于有人偶然发现这个问题。

我的应用程序在本地连接正常,但在远程连接失败,问题是它需要一个身份并被允许访问密钥保管库。

有关如何设置的更多详细信息步骤,请参阅此 Azure web app and managed identity to access key vault

答案 2 :(得分:1)

  

Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:参数:连接字符串:[未指定连接字符串],资源:https://vault.azure.net

AzureServiceTokenProvider尝试使用服务的托管身份获取令牌以访问保险柜时,实际上会发生错误。

1。在AzureServiceTokenProvider的connectionString参数中传递“ RunAs=App;”。这样,它将不会尝试使用不同的模式来获取令牌,并且例外情况要好一些。

2。安装/更新Microsoft.Azure.Services.AppAuthentication的最新版本。

启用MSI并拒绝访问时,请检查Azure密钥库访问策略>添加访问策略,并使用获取秘密权限添加MSI服务原则。请参阅此article