Keep access tokens private in open source iOS apps

An app using the Mapbox iOS SDK must provide an access token to display Mapbox-hosted maps. If the app’s source code is made public, for example on GitHub, you should rotate your access token regularly to prevent abuse by other developers. You can go one step further by keeping your access token out of the project’s repository entirely:

  1. Create a new plain text file containing your access token. To avoid accidentally committing this file, either save it to a location outside your checkout (such as ~/.mapbox) or add the file to your project’s .gitignore file.
  2. Open your project in Xcode. In the project editor, go to the Build Phases tab, then click the + button to add a new Run Script phase to the end.
  3. Customize the Run Script build phase to run the following code (replacing ~/.mapbox with the path to the file you added in step 1):
token_file=~/.mapbox
token="$(cat $token_file)"
if [ "$token" ]; then
  plutil -replace MGLMapboxAccessToken -string $token "$TARGET_BUILD_DIR/$INFOPLIST_PATH"
else
  echo 'error: Missing Mapbox access token'
  open 'https://www.mapbox.com/studio/account/tokens/'
  echo "error: Get an access token from <https://www.mapbox.com/studio/account/tokens/>, then create a new file at $token_file that contains the access token."
exit 1
fi

Optionally, you can also add the path to the access token file to the build phase’s list of input files. That way, if you change the access token, Xcode will automatically update Info.plist.

When building the project in Xcode, the access token will be inserted into the Info.plist inside your built app, but not into the Info.plist that you’d commit.

Additional questions? Ask our support team or learn more about How Mapbox Works.