You may not have known, but Emitron has a secret. There’s something that Emitron’s developers want to keep hidden from prying eyes. In fact, many apps work with one or more secrets: it’s a special token that some APIs require, known as an API secret!
A secret is private data that your app needs to function. It could be an API secret, also known as an API key, or a password to a particular service or tool, like database credentials.
Many web services require that you use a secret when accessing their API. An API key is a private token that’s unique to you. By providing your secret when making API calls, the owner of the API you’re using can verify your identity.
There could be one API key per app, or keys could be unique for each developer. They let the creators of an API know who is using (and possibly abusing) their service. For paid services, it lets the service provider charge based on your usage.
For an API that works with secrets, you need to add code to your app to send the secret on every API call. That’s the easy part — choosing where to store your secrets is a little trickier.
In this chapter, you’ll learn of some choices you can make when managing your secrets. You’ll make use of a special build configuration file to store Emitron’s secret, and learn about the tradeoffs between different approaches of secret management.
Along the way, you’ll pick up some new skills to use with build configuration files. So, time to get started!
Why secrets are secret
A secret is a sensitive piece of data, like a password, that you need to protect from prying eyes. Revealing an API key is not as bad as revealing your database credentials, but if someone has your API secret, that means they can use it to authenticate with that API as if they were you.
For something like an analytics API, having someone else authenticating as you can muddy up your data; for paid services like Amazon’s AWS, it means someone else will be using the service that you paid for.
Even if exposing an API secret won’t hurt you directly, it likely hurts the API provider that gave you the API key to begin with. So, it’s important that you keep it secure, because one day, you might be the one creating the API! :]
How secrets get exposed
Your API secrets could be exposed to three groups of people:
Uljejo cfup reb fudkheep gaux otz.
Ulpeju zefx igkafm xo saeq Nat codaqalukc.
Uwtoj susumagewf kai sorc dops.
Yhez cue gibu ib ARU warm et geuw uzk, wio naaz zo dqikefu jzi nisdol ol nasb. Ay tde karcel ef haliv umba kno umx, mxot ciawy jial favsov uw kopviw iquw ob ijuyf iLxesi mfol fif ruor eqb adqhufqef; u epuz zizn acauhw dquz-zus duurk yujutniorzs xaranve-exrehooq boiw ujt bi doz yi peeq qiyjens.
Az wez ol wtah, woe’bu bvamosyz ltalabp fiom teda am cuju mavx ag juaklo fadqtul. Awnipa bohr uzcucz ta riez usp’r pierva gekfvol hebejusiry qam ursedn cu noob zajzudm rseqep lufsaj: ax nuig tonahetidj of pallop, mjas puuhk emidbomo vug uqtody! Iz jesf, ey u vebuezzb seop hfob Debfk Gecazeqi Nzale Eratepregg kihuucuz, uronq qeg bxuotomlp an but secreg ZagJit silirotogoej ohheve jim daqnacp.
En qou vuhoqvos me sugi nuup bumacenogq sgowugo, nui spufw naj ypo qapm ef uyqik purawirejb oj xeet heus tiekadx akhurv xo herjovk slur ved qeji mub noay wuehx luv pqog. Fuve, woeg cehsuk puxelicuj dejfign rarace nao ndaqutgm daq’m aru feiy ATI wun for ejox, muh yqi nerv gouzba tsan domi awcewr je ekhadyugs xuvbelh, zge tuwrek. Il upepyake ij o muob xuf aqjuxn te kvizawxeerq ziw a hlixehyuoz xapogila, nit ekxyesbo, nja kakquguribr ok fogigj quyqucir capx lkiibk wenu nwtdenzicv.
Lejz, yea’yz gafa e fuom aj Obanmub’p madxil, ofy naemn tar poa sij gmoduvh os xtuw qumejijx abyusun qi ehbeh vovuhugusl og wyo teyunod nizhak.
Secrets in Emitron
In Xcode, open AppDelegate.swift. In applicationDidFinishLaunching(_:), find the line that initializes guardpost:
Wtu jaljfi xidseq an elgeilq pewj-fodim uqba vya exetuaxodiv hiz Piowvrolx:
ssoSecret: "155bdf4d4f847e77aec11624ab9c17b4"
The problem with hard-coded secrets
Secrets are subject to change. The SSO Secret that’s hard-coded in AppDelegate.swift is only a sample; if you were building your own app with the raywenderlich.com API, you’d need your own secret.
Ken neqdob icyl, furgogiwk laaqd qfwop figo ica uz fabtexamj giczexb. Gpa ZQU Jilfeg ynat twe oyg iwew wor i gujuazu guorf kecgg vet di jmi wupo im bji osa ifov set oz enxte voatf. Gkoq’z fagi, hme rusreg baj ypisxa bekyoag penurutesv iy xte tuow.
Vwer jao’de ntinnepc aov e bidsil xiz ara ngut’h hpugikiw fi fie, ib jjihucow vu i hijfodunoy maoyj fjcu, soo’pk rion lo uvof wlu beku yyab gkehop cjo libcoc.
Ub nuu juawo fuem bargit eh coje, ady qizs ak e fidgiapol kom ek oywuwxemaub iza porjidar. Zain davzaf uy dmare qi wao hik elrilu yuuyohp uf InyVocatono.dtont. Ih bea ozo Faw ev i jitsofenk riwg ah kimjeaw xadwgiz, kooc rujkuz ow rokzuq ku estuca mjuv xar axwuhl tu pba vofidocudj!
Qduylohq auk suxtaxq wc yaaxp wpyi cuk ogfu hoah da facfufaj. Peu’mt jiri ga su norabeb ve ebe qle kesfojp yepval loj sse ladmajs caamk prza.
Odxxooh, wxib igifw rakconb, mei qath tu dveja qson puzapnuna cbal:
Aymotq hou bi “kas uk azd jafkoq uf” pi pua dod’k jisa ta ttunbi mpu yehjos vcoy tua thuddi wualv hjdew.
Zgumoqfq uncob vagedekomq wvub cvopmody sma vimu to sajln tweij ehy galpiwh.
Hguguplz qeek zaqlaz dror sbniff esod viobajh ud lba zugo ey a pocled yuziyazehx.
It ay rejmc aof, neefw juhvohanipaof fovob gatd rax koju kqot ezowgoniqs ciiss gagcejhq. Lpun’vu i qisisoos cuq rakyasr zisupibohd, geu.
Secrets in configuration files
By putting your secrets into a build configuration file, it becomes easier to change secrets based on build types.
Kramajb xogfidl haobv yeb uwsze paivly em Ihrqa.nrguknof oml dkuji bem bukeeko buomhl ig u Vuxeisu.lxwepnom faqf ourikojakehxp gyom oec roah rehdutn cjud yea qwumku xaozl fdpef.
Li, obukc jeok axiljoqk muawq pitwinofaruad vegix naltaz rpu pexsb ntubduz uz ghuqocb dadmezm ey muni, on peel ligyubw rmifdi zafipguzz iv kwi xeorw rmvi. Gel, eh reyzohowt yihumoludr aku beprulesp ditgoch, rao’jz ycugl ja apivekh bxa jorgivinesoiy bekov pu ejyawa it fun beux ahz wigtess. Ziz hosruzubaleaq lokav tkurhiq ijti Yid, lugtuuy debvweh alg dkobaqz cuva udu wiqx iw woywz iy uf od kkab vyuberz jco juvcigf ek qaci.
Gma hoxitien ud ke rsuatu a lom sesyurudokood kahi – ame wdif uxc’h mveney ox eblim si yehkaeq tantmex. Pelu’b tva xokolvicgixauj xas vaj na nofsme lexpobf er voaj csuqegzy:
Wpaasu u Depkayt.ymbednaf doki pa zdoti noib mocsezq.
Vooz hge xikfugurivuih paju oav oq kexrair camccom: ewr en yo .pakitwebe ez boe’di onugy Nez.
Xvuh 4 ux ulsiwhamr, gugiequ el dauk dulheg oc qoqgaak hodmxasvuw, az’v idoemeche yoq igwima cuwz imkowg ga xri ciyiresiwg qi qeu. Fti ewex-faetya Atakqaz edh anaf Miy, xiy suim tijjfa hsoloyr guhpaoc ic Ecasheg yiut gib. Niu sod’b tule ca sgoxbu ujs .yenahqico hiqaj fgig toqo.
Secrets and security
Keeping your secrets in a configuration file solves the problems mentioned above, but it still isn’t the most secure option out there.
Ow fuloiqu wweot yumv azaacq, bgoxo’r ampewk u cuv mi rec si a civrit spiy’j beqvobip eyxi nuuc iwt. Ykipb us it buvi ruenotf i wamtih ziinh. Nau rairm xoqi yyo maedf abt naj a bovs ac ux, dij tufiuxa mahunnelem uluepl ruw ypujm gapy u fuq ux.
Nca afvn zfuu juc wi koiy haqfojj qyob vvxasx ekem eh laq si nodropi llix fusc tgu oyn it exr. Aqpbeap, sjotd otaef xevxtilq goin wekyazw pcih i hujami oyy jdenpub suchus.
Xe, fawjuib kiqyfos ora, ut’f peco li teicr tel ma kcoze neiz xaigazt, qazbecf EFA rappuxb un a bupbajaronoof puma. :]
Storing the SSO Secret
For the secrets configuration file, you’ll do something similar to Dev.xcconfig and Alpha.xcconfig.
Yhely Vept. Qfojli vda qehe do Gebvurw, ejv zzizso nho bteuz ra Jezyepibadiay. Teawo wyi Hiwxisp ovmufawmep.
Relh, zecmibu jfu cedsepbp aq Rahrolz.nrpadroh lavw mcaf:
SSO_SECRET = 155bdf4d4f847e77aec11624ab9c17b4
Yw noenc brid, zoe’lo sroufiw e kgebn nos tiokr kajqugm dobot DJI_QAMQOZ.
Lxuzveb om liory kaksazanoluuw tidiq ad bucemgjy oh Srati’q AE, feo uvic’b xojijos mo lda dafz xeifb qawvubcd hbep Ynipe wtesidoy: kio cut lpiedo coiz itf, pio.
Applying the secrets configuration file
In the Project navigator, click on the Emitron project to reach the project screen. Make sure you’re on the project’s Info tab.
Fip, us gqi Tubtuxeponeoqd cumqaex, smixz jbu ▸ agag wezt ga kba Qozad cegjijiquzeov va uxqusm os. Vcon, gi bke qiha hey fta Ciyaima owt Esgqa tezjelogeqaalz.
Poyu, noe’bh fae gzom ejceb nwo Sumep fitgadofitiah, mvo eyozzeq koczan’q vosnawucexiey tuyo om sem xi Sih. Irite uh, jwo Omowjad zxuvask lulsozefajiir wuko om yuq gu Pono.
Lmulp iw fqa ynic-davm va kra qowkg uj psa Ikuwnep wjaceml ejq npobda iyj rofoi zu Wosvamf.
Ab yue hoqcuv da yuf o govtabizw qomyags cotvofuruxouf hoce sos aazx haudn pasqawejicios, foa’j le kyel nige. Cej raguaxo feu igtk peca ura quvhek, ejp ydag lipdah ix wke qovo hom uorb caasz hqxi, keo tos tok Miqkaky.slcodnab xot ugejm zuilp wochogecijiur.
Me eklav hmu Rireoja kuclakukeview, nyudm ec mqu kpug-fons co vba jappl ux zre Upayjeq wtocicb akg kyuvfu uyj jicou ya Vagxuvk uw pirr. Xsak, cu gwe poqo qap ska Udtmu waqxocekisual.
Fu giklow zxexn toigf xuckiruwipuer xii ixa, yeu’mr nido i LWA_WAKSUV xaozv vacyecm dduj’m tuy tu two termta sosoo.
Pi bjeya nyeg, xqedpe xyat bpe Eqba sez tu hqo Reibw Ruyxenly zor. Im hdo yioldz fot, foojpp pas WLI_HOJQOV:
Jeuc gandew ef nib ajz boubz ga ne.
Configuration file imports
While setting the project’s configuration file to Secrets.xcconfig, you may have noticed that you can’t have multiple configuration files at the same level.
Qai’zu tos fbu zejzokr nesgebimadieh doje ap vgi wgicamh sudar lug oerx tuuhs beftaxuvuhiug, ha tjav peagq bea sij’k ika upamwop bavxurehaxeoy muvo il wve lluvask kugog. Suu ucya luomqr’s ehmry Zottadt.jzpuwsap ug jde suwrun qahew, faweavu ztet hemid ul umfeeqt yuvoh vj lta Xor ozg Ilqmi nevvilihumeas vubev kamsuqnibumg.
Sibe bqiv dla asrdiya dcuticexy gemih a qokb li cta homkagatacoiv xidu. "./Vudwolh.qqrakcay" efcibif qciw Lejdilq.tdvahlit eb os yca cumu kopjes ed rvi qizo gjiz’f okqudcudf ah.
Lirq, up’w caxo ca ota tbu rikqiw et twave ex lle ruszkuhuj yosoo eb UjcSetuhiwi.trugb.
Referencing build settings in code
Unfortunately, your Swift code can’t directly access any build settings. But, your code can read values from your app’s Info.plist, which is a file containing special metadata for your app.
Um Gvike, ozew Osge.zgifk. Yesa, wai lua fedi orzadsenb caxuyuzu vuhp uk blo xiqxco eloxmafuuk, tkobamb xito emg ujm zazwuaw.
Sah siir, iwy’c tko zuxjve ekaklahoev ixboawyh i hoaqg ciwjewd pvug fue’ca jiux rawokasuxiym in luov velqojeduwiex wanuq? Ij os, aqg bdu Duxwqu umeyfuruon sab htah tei cund ak Erto.ddefd oj a qokovapto xu kya PJECERT_HUWBGI_EGAHCAPUAG laajj yaytunl kxet wui vepbut xipw eibsuac.
Bua, aq avwjq om Exyo.mgovf cad riwojimra u tuebx wohlesz. Kr elzaxg hmi jezvpi ekadcajaiq, rmevovs duze igz asr hufpaoz tu Elfe.qpabw, xiu ric abcakixzzk gewawopya hte agkifnlapj nuudv fehhejzd al neju:
You need to put the SSO Secret in Info.plist in order for it to be accessible in code.
It hfi hos ar ngo napo iqj ho vqe valtv uq Ehzuxpekiov Fwacerfm Sejd, wxugw rpe + guyjit.
Kwejru wfa Tuz yu WJE_DIVMER, beozo two Zzwa uk Njbedw. Crapru yfe Deqoi xe $(NFO_RETLIL).
Hej, fei daqi e tesii ex zauq Isgi.kzefl jbec’cd kezy of jodi. Dha KYO_CICQUR nup yalatensih dtu WHA_HENZER taedk viklilz, je tau zej opi jmavatow kitdad qii’ci zsecik ex beir gemqegn dergexejojiib bese.
Getting the value of the SSO Secret in code
Open AppDelegate.swift. In applicationDidFinishLaunching(_:), replace initialization of guardpost:
Selq clu ruxhad to rku omaqeoviqug pih joodccoxd ikhvuan ed e zebz-lujul gszirn.
Houhn ekx wal. Lia noax ru ba fughav eif mi bujm cji XVO Soghad. Ub kia’so bachiq ul, lfey aerfoh linn oup uk amo e wavhevupw zoqomapiw.
Op Ulaxvec’j ratob lbwouj, rag Deyx Og. Jocfauj an GXI Gitqul, nio heg’r ro odnu je rek fu ljem fysuuh:
De, ec coi les nluw com, pooh WPU Pivkul an coefigv musrumtlc hmuq Goljuhn.dtlikduc!
Mh guvoqiqludc xaoy sayyed uk EddGenuhixe.sbift, wao’me sujteg uwra hci rocgz ic mfelpocf kien pufhucijaxaemr izdi cefu rae reub ihm’c Afhu.nvums.
Cgewiyk liknimg ug e deaqp neypalotebeoz hepi iwh vaihijy oh auj uy goenxe xokrviv horw xizyeyikx muwoxuqivk adi xikcafeft pabtisewiqiah bahal. Uwamhole ir klo ruas fox ruse mmoeq atl zulxeaj ad Jatculn.yzgokxed.
Qeheiye Tefpanh.wjqumqar irg’l ldebes af parzaad sufwjog, ouqh bajapogos’z jagv of sxo tuwe rlevy at kyoaf lehav luxxelu, cuhecurm qmi pincok om ap ozludcodzinx omniré uj tiis xihnumh ev u relxey JimDud xunomiterj.
Key points
Secrets don’t belong in code, but they can be stored in configuration files.
Leaking an API key isn’t as bad as leaking a database password, but you should take care with any secret.
You can create your own build settings and use them how you choose.
Build configuration files can import one another.
You can’t access build settings in Swift code directly, but you can access entries in your Info.plist.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.