I'm currently in the process of open sourcing Fructika, an app I built at the beginning of this year as a side project to look up the fructose level in common foods. Fructika is a Xamarin Forms mobile app built for iOS and Android and, like many side projects, when I was building it I took a few shortcuts that make the open sourcing process less simple than just throwing the source code open on GitHub. One of these was including secrets in the source code, yes I know 🙀.

Fructika is hooked up to AppCenter for CI/CD and so off I went to look at the docs and find out how to inject a secret as part of a build. After all this must be a common use case I thought so there must be a really easy way to do it. Much googling and one StackOverflow question later I realised that no this wasn't as simple as I hoped and if it was my google fu was letting me down. Then I found the wonderful Mobile.BuildTools NuGet package by Dan Siegel and after a few false starts and me asking Dan some dumb questions I realised that yes this can be as simple as I always dreamed! So here's a quick rundown of how you can easily extract secrets from your source code and inject them when building on AppCenter.

1. Install the Mobile.BuildTools NuGet package in your project.

2. Add a secrets.json file in the root of your project (this should be excluded from source control using .gitignore).

3. Add your secret(s) to the secrets.json file, for this example I'm going to add a SearchApiKey but obviously you can add as many secrets as you want:  

{
  "SearchApiKey": "SUPERSECRETGOESHERE"
}

2. Build your project locally and this will generate a static class, Secrets.cs, with a property SearchApiKey. You can find it under the obj folder if you want to have a look at it and it will be regenerated on every build.

4. You can now access this class and it's properties in your code like you would any other static class, for example:

var searchApiKey = Secrets.SearchApiKey;

5. Finally to pass the secret into your build on AppCenter you need to add an Environment variable to your Build configuration that matches the property name prepended with Secret_ and set it's value. So in my case the Environment variable is named Secret_SearchApiKey as you can see below.

Build configuration -> Environment variables

You can check out the Mobile.BuildTools GitHub repository for more information.   Â