Hiding private details from open source projects

后端 未结 4 504
轻奢々
轻奢々 2021-02-11 07:39

I have a .net github project that is basically a wrapper around a web API. In the test project, I am calling to the API using an API key. I need to keep this key private, how do

相关标签:
4条回答
  • 2021-02-11 08:00

    Perhaps you can store the key outside of the Config.cs file and load it at run time.

    Bonus, other people using your code won't have to recompile the project to change to their API key.

    0 讨论(0)
  • 2021-02-11 08:05

    One option is to use .config files instead of having secret keys hardcoded in sources.

    More info Using Settings in C# and step-by-step guide

    <configuration>
       <appSettings>
          <add key="SecretKey" value="0" />
       </appSettings>
    </configuration>
    
    
    var secretKey = ConfigurationManager.AppSettings.Get("SecretKey");
    
    0 讨论(0)
  • 2021-02-11 08:07

    You are probably looking for the App.config file for a project. It will be copied to <application>.exe.config when you compile it. Users can edit that config file as needed.

    In that config file, you can add your API keys:

    <configuration>
        <appSettings>
            <add key="APIKey" value="12345"/>
        </appSettings>
    </configuration>
    

    Then you can access it from your code using ConfigurationManager.AppSettings:

    string apiKey = ConfigurationManager.AppSettings["APIKey"];
    
    0 讨论(0)
  • 2021-02-11 08:25

    This is the perfect for .config files. Depending on whether its a web or console application, you will have a web.config or app.config file in your project.

    You can use the appSettings section to store your API key.

    To make things even easier, you can actually have this section read from another file, ie: specialappsettings.config and then just ignore that single file from your repository.

    Modify your web.config (or app.config):

    <configuration>
    <appSettings file="specialappsettings.config">
    </appSettings>
    <system.web>
    <!-- standard web settings go here -->
    </system.web>
    </configuration>
    

    Create a new specialappsettings.config file:

    <appSettings>
    <add key="APIKey" value="YourApiKeyValue" />
    <add key="AnotherKey" value="AnotherValue" />
    </appSettings>
    

    This can be accessed in your code via:

    var apiKey = ConfigurationManager.AppSettings["APIKey"];
    

    Notes:

    • You can keep your settings within the original web.config file as well but this lets you ignore just the specific settings file from your git repository without affecting the rest of the project's necessary configuration details.
    • The same "key" can be saved in either file however the external file will override the original web.config file value.
    0 讨论(0)
提交回复
热议问题