Keep access tokens private in open source iOS apps
An app using the Mapbox Maps SDK for iOS 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:
- Create a new plain text file containing your access token, named either
mapbox. To avoid accidentally committing this file to an open-source project, either you can save it to a location outside your project's version-controlled directory, or you can add this file to your project’s .gitignore file.
- 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.
Customize the Run Script build phase to run the following code (replacing
~/mapboxwith the path to the file you added in step 1):
# Look for a global file named 'mapbox' or '.mapbox' within the home directory token_file=~/.mapbox token_file2=~/mapbox token="$(cat $token_file 2>/dev/null || cat $token_file2 2>/dev/null)" if [ "$token" ]; then plutil -replace MGLMapboxAccessToken -string $token "$TARGET_BUILD_DIR/$INFOPLIST_PATH" else echo 'warning: Missing Mapbox access token' open 'https://www.mapbox.com/account/access-tokens/' echo "warning: Get an access token from <https://www.mapbox.com/account/access-tokens/>, then create a new file at $token_file or $token_file2 that contains the access token." fi
$(TARGET_BUILD_DIR)/$(INFOPLIST_PATH)to the build phase’s Input Files section. Otherwise, the access token may be overridden during incremental builds. Optionally, you can also add
~/mapboxto this section, so that Xcode will automatically update Info.plist after you change your access token.
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.