Search code examples
c#gitapi-key

Proper way to hide API keys in Git


In my C# project have APIKeys.cs file which have const strings with API keys. I want those strings to be empty in Git server but have actual API keys in my local computer. So peoples who pull project can compile it without problem and still my local computer gonna have API keys in same file.

If I try to upload APIKeys.cs file with empty strings then I can't have local file with API keys because when I try to push it, it will overwrite empty APIKeys.cs file. Also I can't ignore this file too because it will remove empty APIKeys.cs file from Git server.

So what is best automated approach for this problem which will allow class file with empty strings in server, so project will be compileable when people pull it and have real class file in local computer?


Solution

  • I figured another solution now which is not perfect but still good enough for me, example:

    APIKeys.cs file:

    public static partial class APIKeys
    {
        public static readonly string ImgurClientID = "";
        public static readonly string ImgurClientSecret = "";
        public static readonly string GoogleClientID = "";
        public static readonly string GoogleClientSecret = "";
        public static readonly string PastebinKey = "";
        ...
    }
    

    APIKeysLocal.cs file:

    public static partial class APIKeys
    {
        static APIKeys()
        {
            ImgurClientID = "1234567890";
            ImgurClientSecret = "1234567890";
            GoogleClientID = "1234567890";
            GoogleClientSecret = "1234567890";
            PastebinKey = "1234567890";
            ...
         }
    }
    

    Ignore APIKeysLocal.cs file in Git and people who don't have this file can still be able to compile project if they remove this file from solution explorer.

    I also automatically create empty APIKeysLocal.cs file if it is not already exists using project pre build event:

    cd $(ProjectDir)APIKeys\
    
    if not exist APIKeysLocal.cs (
        type nul > APIKeysLocal.cs
    )
    

    That way user don't need to do anything to be able to compile project.