Developing a secure .NET 8 (core) console application

In this post we will develop a .NET 8 console application which reads the configuration values from environment variables. This enables us deploy the application in an EKS cluster and read the config values from any secure secret storage.

The develoment environment

Docker configuration

To prevent Visual Studio from debugging in Docker containers

Debugging in Docker containers provides a stable, production like environment for your application, but larger applications can take a long time to build into containers. To stop Visual Studio debugging in Docker containers see Prevent Visual Studio 2022 from debugging in Docker. Official documentation is at Project warmup.

To allow Visual Studio to debug in Docker containers

If you want to debug in Docker containers to see how your application will run in production

Enable Docker Desktop execution

To be able to start Docker Desktop on Windows your user id has to be in the docker-users local user group. To add your user to the group

  • Open a command prompt as Administrator
  • Get the username:
whoami

Add the user to the docker-users user group:

net localgroup docker-users "your-user-id" /ADD

Log out and log in into Windows for the change to take effect.

Enable WSL (Windows Subsystem for Linux) for better performance with Docker Desktop

If Docker Desktop recommends using WSL instead of Hyper-V and WSL is not installed on your computer

  • Open an Administrator PowerShell window and execute
Enable-WindowsOptionalFeature -Online -FeatureName $("VirtualMachinePlatform", "Microsoft-Windows-Subsystem-Linux")

Restart the computer for the change to take effect.

You may need to install and enable the WSL2 Linux kernel. See Step 4 – Download the Linux kernel update package for details. Don’t forget to activate the WSL2 kernel with

wsl --set-default-version 2

Application settings

Create the application

  • Start Visual Studio 2022 community edition or newer
  • Create a new Console application using the C# programming language

Create the git repository

IMPORTANT!!!
To exclude the .env file and other temporary and build files from the Git commit create the .gitignore file

  • Open a terminal in the root directory of the repository and execute the commands
  • Create the .gitignore file
dotnet new gitignore
  • Create the Git repository
git init

Read the environment variables

Environment variables are the safest and most flexible way to store sensitive configuration values. This way those are never committed to source control.

Install the NuGet packages

To be able to access environment variables we need to install the following NuGet packages

  • Microsoft.Extensions.Configuration.EnvironmentVariables – to read environment variables
  • DotNetEnv – to load environment variables from .env files on the developer workstation

To install the packages from the command line, open a terminal in the project directory and execute

dotnet add package DotNetEnv
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables

Create the local .env file

Create the .env file in the solution directory and add a key value pair

ENVIRONMENT=local

Write the code

Create the Settings.cs class to store the configuration values

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MY_NAMESPACE
{
    internal class Settings
    {
        public string? Environment { get; set; }
        public string? AppName { get; set; }
    }

    public class ConnectionStrings
    {
        public string? SQLServer { get; set; }
    }
}

Create the Configuration.cs class to read the configuration values form the environment variables

using DotNetEnv;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MY_NAMESPACE
{
    internal class Configuration
    {
        /// <summary>
        /// Reads the config values from the environment variables and returns the Settings object
        /// </summary>
        /// <returns></returns>
        public static Settings BuildAppSettings()
        {
            // Try to load the environment variables from the .env file for local development
            // Place the .env file in the root folder of the solution
            DotNetEnv.Env.TraversePath().Load();

            // Read the environment variables
            var environmentConfiguration = new ConfigurationBuilder()
                .AddEnvironmentVariables().Build();

            // Instantiate and populate the Settings object
            var settings = new Settings()
            {
                Environment = environmentConfiguration["ENVIRONMENT"],
                AppName = environmentConfiguration["APPNAME"]
            };

            // Return the Settings object
            return settings;
        }
    }
}

In the Program.cs file call Configuration to load the Settings object from the environment variables.

// See https://aka.ms/new-console-template for more information

using MY_APPLICATION;
using DotNetEnv;
using Microsoft.Extensions.Configuration;

// args is a string array that contains the command line arguments
string[] arguments = args;
Console.WriteLine($"Number of command line arguments {arguments.Length}");

// Read the configuration values
Settings settings = Configuration.BuildAppSettings();
Console.WriteLine($"Envronment: {settings.Environment}");
Console.WriteLine($"AppName: {settings.AppName}");
 

Leave a comment

Your email address will not be published. Required fields are marked *