I have to store user credentials in a web api somewhere. I decided I create a console application in the solution, next to the Web API, that encrypts the data, and writes it to the web api’s appsettings.json.
Here is the relevant code:
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection(o =>
{
o.ApplicationDiscriminator = CoreVariables.SALT;
}
).SetApplicationName("test");
var services = serviceCollection.BuildServiceProvider();
var dataProtector = services.GetRequiredService<IDataProtectionProvider>();
var protector = dataProtector.CreateProtector(CoreVariables.DATA_PROTECTION_REASON);
//Fill username and password, REMOVE AFTER ENCRYPTION, DONT PUSH IT TO REPOSITORY
string username = "";
string password = "";
if (string.IsNullOrEmpty(username))
{
throw new Exception("Username cannot be null or empty.");
}
if (string.IsNullOrEmpty(password))
{
throw new Exception("Username cannot be null or empty.");
}
string protectedUsername = protector.Protect(username);
string protectedPassword = protector.Protect(password);
string appsettingsFilePath =
Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,
"My.API", "appsettings.json");
if (!File.Exists(appsettingsFilePath))
{
throw new Exception($"Cannot find file in path: {appsettingsFilePath}");
}
var appsettingsContent = File.ReadAllText(appsettingsFilePath);
var appsettingsJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(appsettingsContent);
appsettingsJson["User"] = protectedUsername;
appsettingsJson["Secret"] = protectedPassword;
appsettingsJson["SecretLastChanged"] = DateTime.Now.ToString();
var updatedJson = JsonConvert.SerializeObject(appsettingsJson, Formatting.Indented);
File.WriteAllText(appsettingsFilePath, updatedJson);
Then, when I deploy the application, I got an exception, saying The key was not found in the key ring.
Here is the relevant code from the API:
Program.cs:
builder.Services.AddDataProtection(o => {
o.ApplicationDiscriminator = CoreVariables.SALT;
}
).SetApplicationName("test");
Service, where I use it:
public MyService(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(CoreVariables.DATA_PROTECTION_REASON);
}
public async Task<string> Authentication(string userName, string password)
{
string authUsername = _protector.Unprotect(userName);
string authPassword = _protector.Unprotect(password);
}
Does this encryption is somehow connected to computer data? When I deploy the application into a server, the decryption will not work.