web-dev-qa-db-ja.com

Azure Web Appは接続文字列を見つけることができません

私のアプリケーションを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>();

同じ設定を使用してローカルコンピュータから実行するとうまく機能します。しかし、それはサーバー上では機能しません。何か案は?

[〜#〜]更新[〜#〜]

URL 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;
4
renakre

私はこれが承認された答えを持っていることを知っていますが、それは同じエラーメッセージを持っていた私のKeyvaultの問題でそれほど助けませんでしたので、誰かがこの質問につまずくのを助けます。

私のアプリは上質に元気に接続されていましたが、リモートで失敗すると、IDが必要であり、キーボールトへのアクセスが許可されています。

その設定方法については、 Azure Web AppとManaged ID を設定する方法について詳しく説明します。

1
Mocas