Proper way to hide API keys in Git

前端 未结 4 1578
慢半拍i
慢半拍i 2020-12-06 02:39

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. S

4条回答
  •  囚心锁ツ
    2020-12-06 03:28

    Isn't this very similar to the problem of injecting a build number into your component? The way I do that is to have a pre-build step that generates a file called AssemblyVersionInfo.cs based on some environment variable. You could do the same thing with your API Keys.

    In the pre-build step for the component that compiles in the API keys put something like this:-

    if not defined API_KEY set API_KEY=DEFAULT_KEY
    echo public class ApiKeys>"$(SolutionDir)src\ApiKeys.cs"
    echo {>>"$(SolutionDir)src\ApiKeys.cs"
    echo public const string Key="%API_KEY%";>>"$(SolutionDir)src\ApiKeys.cs"
    echo }>>"$(SolutionDir)src\ApiKeys.cs"
    

    Then you set either a user or system environment variable on your local machine with the real key in it.

    setx API_KEY THE_REAL_KEY

    To avoid Git wanting to commit the file just add it to the .gitignore.

提交回复
热议问题