Securing API Credentials

In the iOS Foundations Module 6, Lesson 4, we use the Yelp API key.

  1. What’s the best way to keep this API key secret in GitHub?
  2. In the App Store, do the Apple reviewers need access to your API key?
  3. Can you securely compile the app with the API key, or might someone decompile it to get your secret?

My current solution, so I can publish to my repo is to use something similar to a .env file. However, when I went to create the .env, it warned me that the project wouldn’t be able to read from it. So instead, I created a ProdEnv.swift with a client and apiKey property. Then, I added another file ProdEnvExample.swift that has a comment representing the struct that I reference later with my credentials. Last step was to add the ProdEnv.swift file to the .gitignore, so it does not get committed.

FYI:

  • Chris also explains a similar way with the .gitignore, or removing the API key prior to committing here: CodeWithChris
  • this video explains how to create a .gitignore file at the 6:00 mark: CodeWithChris

ProdEnvExample.swift

/*
 This serves as an example struct struct, so we do not commit our API key within our Git repo.
 Copy the below into a new ProdEnv.swift file, then insert your credentials as shown below

import Foundation

struct YelpAPICreds {
    
    let client = "<insertClientStringHere"
    
    let apiKey = "insertApiKeyHere"
     
}
 */

Then, in my ContentModel, I create an object of this struct, and use the API key in the request header:

 // See ProdEnvExample on how to insert your API credentials
 let apiCreds = YelpAPICreds()
            
 // Add Authorization headers with our API key
 request.addValue("Bearer \(apiCreds.apiKey)", forHTTPHeaderField: "Authorization")

However, I’m curious if there is a better practice, and also how Apple reviews this.

This article has some good point about having Secrets, but sadly the main point it makes is just to not have any (which is unavoidable)

You’ve done it, you have some kind of secrets file and you do not commit it to GitHub by using the .gitignore

No, the secret is in your app bundle the app reviewers don’t care about the code, only how the app works

Technically someone who has jailbroken their phone can see a lot more, but also think if your users, are they people who are likely to jailbreak a phone and do this.
But overall that risk is minimal.
There’s always a way to reverse engineer something, just think of the likelihood of this happening.

Hey thanks so much Mikaela!

Glad the reviewers only care about how the app works, and don’t get these secrets.

That makes sense. One of the great benefits of delivering compiled apps!

I was thinking previously that the professionals may know a way to keep this all secret once on the App Store in a different way.

1 Like