Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely store API credentials in a C# file shared on GitHub?

Tags:

c#

.net

api-key

api

I'm making a client app for Windows 10. I have a problem where I'd like to open-source my code, but leave the API key invisible to other people. This is the relevant portion of my source file:

private const string ApiKey = "YOUR_API_KEY";

I'd like to have this transformed to

private const string ApiKey = "THE_ACTUAL_API_KEY";

when it is compiled. How would I go about doing this?


edit: Sorry for any ambiguities; I was asking how to prevent viewers of the source code on GitHub from seeing the string, whilst not having to change it during local builds. This question does not relate to encryption in any way.

like image 474
James Ko Avatar asked Jan 27 '16 18:01

James Ko


1 Answers

Here's how I ended up solving the problem.

I added a class to my project called Credentials.cs:

public static class Credentials
{
    public const string ApiKey = "YOUR_API_KEY";
}

All further references to the API key were made via the field I added. For example:

public void MakeRequest()
{
    var client = new ApiClient(Credentials.ApiKey);
    client.DoSomething();
}

Now for the magical part. After committing that file via Git, I ran git update-index --assume-unchanged Credentials.cs, which (as per this SO answer) tells Git to stop tracking changes to the file. In other words, if you modify the file and run git diff or git status, nothing will show up.

Then I replaced YOUR_API_KEY with the actual API key in the file, and now everything works perfectly.

like image 139
James Ko Avatar answered Oct 31 '22 06:10

James Ko