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



我只是想在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:localLocalAppData.IdentityServiceAzureServiceAuthtokenprovider.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:UsersErkan ErsourcereposSynergyProgram.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;

对我来说,当我在本地运行函数应用并更改Microsoft密码时,就会发生这种情况, 由于登录的用户凭据用于托管标识的授权, 尝试重新输入凭据

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

当 AzureServiceTokenProvider 尝试获取令牌以使用服务的托管标识访问保管库时,实际上会发生此错误。

1.在 AzureServiceTokenProvider 的连接字符串参数中传递"RunAs=App;"。这样它就不会尝试不同的模式来获取令牌,并且例外情况要好一些。

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

启用 MSI 并拒绝访问时,请检查 Azure 密钥保管库访问策略>添加访问策略,并添加具有获取机密权限的 MSI 服务主体。请参阅此文章。

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

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

请参阅此处,了解有关如何设置的更多详细信息步骤 用于访问密钥保管库的 Azure Web 应用和托管标识

最新更新