In this tutorial, we will learn how to hide API secrets in .NET.
To hide secrets from being exposed first in your CLI execute the following command:-
Run the following command from the directory in which the project file exists:
dotnet user-secrets init
Then write the following code in the console to create secret data:
dotnet user-secrets set "Movies:ServiceApiKey" "12345"
To remove the secret key you can use the following command:
dotnet user-secrets remove "Movies:ConnectionString"
To list secret keys:
dotnet user-secrets list
To clear all secret keys:
dotnet user-secrets clear
Now configure Program.cs to use secret keys:
var builder = WebApplication.CreateBuilder(args);
var movieApiKey = builder.Configuration["Movies:ServiceApiKey"];
var app = builder.Build();
app.MapGet("/", () => movieApiKey);
app.Run();
Read the secret key in your file using Iconfiguration:
public class IndexModel : PageModel
{
private readonly IConfiguration _config;
public IndexModel(IConfiguration config)
{
_config = config;
}
public void OnGet()
{
var moviesApiKey = _config["Movies:ServiceApiKey"];
// call Movies service with the API key
}
}
For detailed information Visit this page:- https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows#register-the-user-secrets-configuration-source
Comments
Post a Comment