Author : HASSAN MD TAREQ

App Secrets in aspnet core

  • Caution:
    • Passwords or other sensitive data should not be committed to source control
    • Production secrets shouldn’t be used for development or test
    • Secrets shouldn’t be deployed with the app
  • Solution: Secret Manager
    • For storing and retrieving sensitive data during development of an ASP.NET Core app on a development machine
    • Never store passwords or other sensitive data in source code (hardcoded, appsettings.json)
  • Development Time
    • Secret Manager create secrets.json file that would not be committed into VCS
    • Configurations in secrets.json is available via IConfiguration Configuration (DI) Production:
    • Use Secrets should be made available in the production environment through a controlled means
    • Use Environment variables
    • Or use Azure Key Vault

Social login providers assign Application Id and Application Secret tokens during the registration process. The exact token names vary by provider. These tokens represent the credentials your app uses to access their API. The tokens constitute the “secrets” that can be linked to your app configuration with the help of Secret Manager. Secret Manager is a more secure alternative to storing the tokens in a configuration file, such as appsettings.json.

Creating Secrets

  • Right Click on the project > Manage User Secrets
  • VS will create and open secrets.json
  • Right Click on the project > Edit Project Files > UserSecretsId section should be added

secrets.json

{
  "Foo": {
    "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true",
    "ApiKey": "12345"
  }
}

Accessing App Secrets

  • User secrets configuration source is automatically added in development mode when the project calls CreateDefaultBuilder to initialize a new instance of the host with preconfigured defaults
  • CreateDefaultBuilder calls AddUserSecrets when the EnvironmentName is Development
  • When CreateDefaultBuilder isn’t called, add the user secrets configuration source explicitly by calling AddUserSecrets

User secrets can be retrieved via the Configuration API:

public class Startup
{
    public IConfiguration Configuration { get; }
	
    private string _apiKey = null;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }


    public void ConfigureServices(IServiceCollection services)
    {
        _apiKey = Configuration["Foo:ApiKey"];
    }

    public void Configure(IApplicationBuilder app)
    {
        // use _apiKey here if needed
    }
}

See