Asp.net

Azure Web 應用找不到連接字元串

  • January 24, 2021

我只是想在 Azure 中將我的應用程序作為 Web 應用程序發布。我一直面臨有關連接字元串的問題。伺服器無法辨識連接字元串是什麼,您可以從下面的錯誤中看到:

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;

Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProviderException:參數:連接字元串:

$$ No connection string specified $$,資源:https ://vault.azure.net

當 AzureServiceTokenProvider 嘗試獲取令牌以使用服務的託管標識訪問 Vault 時,實際上會發生該錯誤。

1.在AzureServiceTokenProvider的connectionString參數中傳遞“ RunAs=App;”。這樣它就不會嘗試不同的模式來獲取token,而且異常會好一些。

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

當您啟用 MSI 並拒絕訪問時,請檢查 Azure keyvault 訪問策略>添加訪問策略並添加您的 MSI 服務原則和獲取機密權限。參考這篇文章

對我來說,當我在本地執行我的函式應用程序並更改我的 Microsoft 密碼時會發生這種情況,因為登錄的使用者憑據用於授權託管身份,請嘗試重新輸入您的憑據

引用自:https://stackoverflow.com/questions/57450422