how i can encrypt sections inside my appsettings.json hosted inside a
remote shared hosting provider inside IIS? i am fine with keeping the
password inside visual studio project, but i want to encrypt the
hosted appsettings.json? is this possible?
First, you need to encrypt the password in some way. Here you have a lot of choices.
The official recommendation is to use Data Protection like this:
string encrytedStr = _protector.Protect("Unencrypted string");
Then, in your project, you will find an appsettings.Development.json file under the appsettings.json file.
By default, the variables used in the development environment are stored in appsettings.Development.json,while the variables used in the production environment are stored in in the appsettings.json file.
So you can put the encrypted content in the appsettings.json file, and put the unencrypted password in the appsettings.Development.json file.
And ensure that their key in json are the same, but the value one is encrypted and the other is unencrypted.
Then, in the controller that calls the password, inject three services of DataProtection, IHostingEnvironment and IConfiguration, and then judge whether the environment is a production or development environment before obtaining the value, and then decide whether to decrypt the value.
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace WebApplication_core_new.Controllers
{
public class DefaultController : Controller
{
private readonly string _environmentName;
private readonly IConfiguration _configuration;
private readonly IDataProtector _protector;
public DefaultController(IHostingEnvironment hostingEnvironment, IConfiguration configuration, IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
_environmentName = hostingEnvironment.EnvironmentName;
_configuration = configuration;
}
public IActionResult Index()
{
// here you can get the data in appsetting.json
string data = _environmentName == "Development" ? _configuration["MySercet"] : _protector.Unprotect(_configuration["MySercet"]);
return View();
}
}
}
In appsetting.json file:
{
//...
"MySercet": "Encrypted string"
}
In appsetting.Development.json file:
{
//...
"MySercet": "Unencrypted string"
}