问题
A common setup with Docker: Two linux containers, one a .NET Core WebServer using EntityFramework Core 2.2.6, the other a MS-SQLServer 2017. Persistent data is being held in a Docker volume. Using docker-compose
, it's not a swarm.
When starting the SQLServer container, one must provide the SA password as an environment variable to the container. However you provide that, it is possible to later read this env from outside the container using docker container inspect
. Which obviously compromises security.
That leads me to two questions:
(discussed in another thread) What better ways are there to provide the SA password to the SQLServer?
The Microsoft help states that it's best to change the SA password directly after starting the container. When I do that in my WebServer code, EntityFramework is already connected with the default SA password (the one I provided as env). I can change the password easily. But how can I tell EntityFramework to reset it's ConnectionString?
Here is my code so far:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<API_DB_Context>(options =>
{
options.UseSqlServer(Configuration["AppSettings:ConnectionString"]);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
app.UseMvc();
using IServiceScope serviceScope = app
.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope();
var context = serviceScope.ServiceProvider.GetService<API_DB_Context>();
var connection = context.Database.GetDbConnection();
// Try connection.open() with changed PW. If that fails, use default PW.
bool needToChangePW = CheckLoginPassword(connection);
// Migration to (create and) update database
context.Database.Migrate();
// Change PW after migration (because maybe the DB didn't exist before)
if (needToChangePW)
{
connection.Open();
context.Database.ExecuteSqlCommand(string.Format("ALTER LOGIN SA WITH PASSWORD='{0}'", SA_CHANGED_PASSWORD));
connection.Close();
// Here I can set the ConnectionString in my Configuration.
// But how can I get EntityFramework to actually use this updated string?!
Configuration["AppSettings:ConnectionString"] = "modified string with new password";
}
}
}
回答1:
Try out this
_dbContext.Database.GetDbConnection().ConnectionString = "your updated connection string";
in your case:
var context = serviceScope.ServiceProvider.GetService<API_DB_Context>();
var connection = context.Database.GetDbConnection();
connection.ConnectionString="modified string with new password";
来源:https://stackoverflow.com/questions/57968605/how-can-i-reset-the-connectionstring-of-entityframework-net-core-webserver