我的 asp.net core MVC Web 应用程序中有以下
appsettings.json
:-
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\ProjectsV13;Database=LandingPage;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"SMTP": {"
"pass": "************"
}
}
我存储 smtp 密码的地方 + 当我将应用程序发布到共享主机提供商时,我将在 appsettings.json 的连接字符串中添加 sql server 用户名和密码。
所以我的问题是如何加密托管在 IIS 内的远程共享托管提供商内的
appsettings.json
内的部分?我可以将密码保留在 Visual Studio 项目中,但我想加密托管的 appsettings.json?这可能吗?
谢谢
我如何加密托管在 appsettings.json 中的部分 IIS 内的远程共享托管提供商?我很乐意保留 Visual Studio 项目内的密码,但我想加密 托管appsettings.json?这可能吗?
首先,您需要以某种方式
encrypt the password
。在这里你有很多选择。
官方建议使用数据保护,如下所示:
string encrytedStr = _protector.Protect("Unencrypted string");
然后,在您的项目中,您将在 appsettings.json 文件下找到一个 appsettings.Development.json 文件。
默认情况下,开发环境中使用的变量存储在appsettings.Development.json中,而生产环境中使用的变量存储在appsettings.json文件中。
所以你可以将加密的内容放在appsettings.json文件中,将未加密的密码放在appsettings.Development.json文件中。
并且保证他们的json中的key是相同的,但是value一个是加密的,另一个是未加密的。
然后在调用密码的控制器中注入
DataProtection
、IHostingEnvironment
、IConfiguration
三个服务,然后在获取值之前判断环境是生产环境还是开发环境,然后决定是否解密值。
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();
}
}
}
在 appsetting.json 文件中:
{
//...
"MySercet": "Encrypted string"
}
在 appsetting.Development.json 文件中:
{
//...
"MySercet": "Unencrypted string"
}
您可以查看我的 NuGet 包ProtectedJson,它无缝集成了 Data Protection api 与 Asp.net Core 中的 IConfiguration