You are developing the app and a time comes when you need to integrate with other systems like Auth0, Firebase, or some other system that you need for your app.
Tip: Never put the secrets in the code and check in to the repository.
I have found that keeping the secrets separate from the code is the best way possible. So how do we do it?
Step 1 - Create a Configuration file
Create a configuration file that will keep the secret variables and the values for your app. e.g. you are integrating RevenueCat in your application to manage the subscription. RevenueCat requires you to create an API key for the purchases and use that in your app.
Select New File and search for Configuration Settings File. Select the template and name the file and create it.
Once the file is created you can add the secret api key in the file. The format you want to follow is <variable name> = <value> e.g. let's name the variable PURCHASES_API_KEY then the value entry in the file will be
PURCHASES_API_KEY = thisIs_yoursecretapikeyforpurchases
Step - 2 Add an entry to info.plist file
Now add a String entry to your info.plist file and reference the variable in the entry as shown below
Step - 3 Access the value in swift
Each source code follows some kind of pattern or something for generic code. Like accessing something from the Bundle, I am posting a sample code that you can use to access the variable but check your source code for any pattern that might be followed for this kind of code, or do what you feel like a good code for you.
var purchaseKey = ""
if let key = Bundle.main.infoDictionary?["PURCHASES_API_KEY"] as? String {
purchaseKey = key
}
else {
purchaseKey = ""
}
Step - 4 Where to keep the secrets
If you are building an enterprise app there will be a CI/CD pipeline and you would save the secrets in the vault provided by the Tooling. e.g. AzureDev Ops or Bitrise etc.
What if you are an Indie dev and you just build the app just on your laptop and just deploy it directly to AppStore connect? Well, you can use some browser-based Password managers and put your secrets there.
Alternatively, you can just create a secure Note by locking the Note.
The choice is completely yours how you want to keep your secrets secrets but never keep them in your source code :)
The same applies to your GoogleServices json file, do not check in the file with your source code. Keep it separate.
Tip: Add these secret files to the gitignore file of your repo so that you never accidentally check in them.
Now, what if you have check-in a secret to your git repo and it is in the history now? Well, subscribe and stay updated with the next post where we talk about how to keep an eye on your secrets in your code and what can you do if you check them in accedently.
Happy coding!!
No comments:
Post a Comment