Issue
I have a Xamarin Forms app which is being built using App Center. The app contains some code that looks like:
var secret= "secretvaluegoeshere";
I then use the secret to communicate with an API. Now I want to extract that secret from code so as not to having it in source control and inject it when building on App Center. Environment Variables seem like they should solve this very problem but the examples in the docs don't mention how they can get into code (only nuget and gradle config). Is there a way to do what I want with Environment Variables or should I be doing this another way?
Solution
So it turns out this is surprisingly easy by following these steps:
Install the Mobile.BuildTools NuGet package in your project.
Add a secrets.json file in the root of your project (this should be excluded from source control using .gitignore).
Add your secret to the secrets.json file, so in my case I'm going to add a SearchApiKey, obviously you can add as many secrets as you want:
{
"SearchApiKey": "SUPERSECRETGOESHERE"
}
Build your project and this will generate a static class called Secrets with a property SearchApiKey, you can find it under the obj folder if you want to have a look at it.
You can now access this class and it's properties in your code so I just do:
var secret = Secrets.SearchApiKey;
Finally to pass the secret into your build on AppCenter you need to add an Environment Variable that matches the property name prepended with Secret_ so in my case it's name is Secret_SearchApiKey and set it's value.
You can check out the Mobile.BuildTools GitHub repository for more information.
Answered By - Adam Cooper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.