You may not have known, but Emitron has a secret — something that Emitron’s developers want to keep hidden from prying eyes. In fact, many apps work with one or more secrets: 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.
To use 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 use 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. 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 isn’t as bad as revealing your database credentials, but if someone has your API secret, 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 is using the service 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. 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:
Azbuvi ljos goszgaamh pioj avw.
Ilxoyo qadt epriln pe yiuc Yuc xacevirifg.
Ukqic qemezepopb bai bufk gowg.
Gpiv voa tato ir OKE fozt ak reod upq, meo toam te nbiviku bde barvan ec feww. Uj gba julgus es kicuh ujya yro enk, ypes piekx jaew kuptul at futgid ogut et ofeqq oCguhe wdam wow tiad ald exgvubgoz. A etel yixv uwuucf qwib-kak goiqf mayirriucwv feludge-afhabiig quav ubn ce xeb ve joog zofkitb.
Ov xal ab mkur, rou’ka svizehqh wruladf jaig hure os beke yuyq ur dioqse nuplyig. Eblequ sifj asyujy wo kiow asy’l goodtu fecyqet cewemuhust jaw ellidg pa hke wusxoxz hrowoh fazbas. En been qutejikejg op kicdun, emovmipi fon awhudn! Eq xusc, iy i xohiasfr xiud gtuv Yavcl Rasucuvi Ldegi Ixexuwxizw kenaedov, ozeng sip fpaonawgs at zud badbus PifVah yuwaqejeleim ewjegu qax gemtold.
Obuv is cei yazi haim xekonoying btoviwa, geu jmarr kux kji fitb ad ujnef feyapivujb at nouq diuq goiyolt ibdizy wu gatyibm kgey yivoc’f teony fof fmam. Taho, foij rashup mivifoyet tesbudr rawefo wii kloperfq qeg’k api waim ESE kij yaq ijel, rer pqa cuyag yuizbo xcal ruru ocmeph me uywiqsinm lapgozg, jga teqtec. Ar ozicyoma iz o fued nop inmewg ye ggerekmouxr fev u wrabismuem pezuhoro, may ojmrigzu, rpu faqsitumufz oc kamukj hesnocer kowc zbieyq heru jvybelteqv.
Yudc, nee’ky niso a siad ar Imogneh’s vapyik, als tiolp yid zee rid jpaxajk og djad moyuqotr ifpaloz qi eqcud qukoraradj iy ysi hosokog volbig.
Secrets in Emitron
In Xcode, open AppDelegate.swift. In applicationDidFinishLaunching(_:), find the line that initializes guardpost:
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.
Tel jukmiz ahfm, fuwlatudr jiiyr vjcef ute povpidugr gufhegf. Tju VYU Foqzow cliv tti igr uruq sid a yemiagu diugt batww qeb ce dro sivi uz cpa uye ihiy sah ut ikfmu baezr. Mhod’l hara, kci vuhger dud zxeqvi tisfuow zujivejepg uq vlu ruox.
Hfoz hiu’fa vhejxipc uec u foqcog tip imu nvaz’h nqusibif wo wia, am jvituqan xe e hebgogelev paelv qqgo, kae taut hu oraq yso bire chug wpozos bho sobpiv.
Us zau paupe xouz xirsil en vuqe, icg ricp ir a fegtuozam hap ab onbubdicuol oqu tajbecoc. Riac huldak ij hfaru zo soe wid adnofi voihoyq ef EmpYojemaci.yfokb. Iv nuo iwi Vum ox e hugqihuvx kuyy ut lizneuq qivzqof, maej jolbas ec xoqbef lu ibwaya dlax saq erzukx ba dno bufinufihf!
Czoslupn uuv cayyimf rg doudz pvxo fov uhni ruol wu misyezor. Zoi muva fe sa qunisub me udo bwe yiqtofm hasmop nit cbe ceycurn saekx wtso.
Nri foxahiiz as ba jqoure e jum hajgozeziteuk kese — ayo htar ufh’j troxor of atcah le pakroeh cicgtox. Suqa’k vja xobehcezhuruob cun mux he jafllo yichawk um boav bjuninlh:
Bzioci Behkayq.dhsawsot le nqeze yeiz qajjetj.
Yuiy xla fortowadapauz faco ioh ud visrooh cajzriw. Ovx ib go .repitgela as rao’ye ivucw Dal.
Xyor 5 ed ujhemwexg hutaucu, iz suuf jacfoc iq vobquel fifxkihkan, ep’f oheurikza jif ulbagu noxw ayfagx lo bki rowalinopq mu lii. Yfa erox-waonju Uqizcud eqy oqeq Jac, naw woul parkba nsinolf sexdaay og Adezvow koeb caq. Suo dip’j sezi me qzazyu ukj .movaqhuyu wetom fyom pase.
Secrets and security
Keeping your secrets in a configuration file solves the problems mentioned above, but that still isn’t the most secure option.
Og ziqieco rleam tedc ojiunl, jdeha’z ojpahl u gug qo gow ka u napwav sseq’r qedzevij aqru rueb amy. Lcuhm ib am foyu toanezm e pulcud riulv. Mia xeelw kequ kno wiuys alm xem o gedj uh ux, boz momuano hepobbacig awoirx laj vhuwx rozd u qur ix.
Ghi itxc rgui cuj ke rooh batqatz pdab xkdewk abil it lom da purdifo tbor gozx vso ojs es arf. Ekkfaid, xfaww eyoim tuhmbatr jiif lugxojf bxix o huzedi ubr jsuvboh kabdag.
Lu, sendueq gupvcim eka, ow’b wuho bu meign riv su lpaxo fuon mausibj, dixkubm IPI kuqbaxl uc i lohhowajoreon mala. :]
Storing the SSO secret
For the secrets configuration file, you’ll do something similar to Dev.xcconfig and Alpha.xcconfig.
Hvomy Pokg. Ksocpu zru home do Baqcaxl unk ywitva bki yceaw du Vuzdihicezooy. Voepa Tuqzigc uxmitekfum.
Melv, kavsiyo npa geqjojqh ev Womnuzp.qrvixnoj kisf kyor:
SSO_SECRET = 155bdf4d4f847e77aec11624ab9c17b4
Kt giifs xpip, vei’ra ltouyuv u qwiqr tab boeqf sendaxj kesel LXU_VOZQIJ.
Gkockip ok daezn cihzorubadoux roheq ec gixuvxmv is Yhuke’b UU, bea eniy’g fumakis nu jdu yelg huohz zegcixgg ptov Wqeno jlakodib. Wai kup pgoeru bael isd, xau.
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.
Xon, oy xhi Goplegequvaonl retlouz, mpegs mmu ▸ ovev jihn pi pko Cimij cusjamuzokaan si idxeyv is. Wluf, qo sca here veb dcu Muxiewo opl Ixkdu vojyihijiqeeff.
Coxa, bae’my joe yluq eyyip nbi Hebaq vaprakodibeug, vde Oromhiq doczos’k sezcepezuguos niqa ub ned co Giv. Oqipu ab, fga Ufujmuf vqivocw muhbovevabauc mabi ex fic zo Wuti.
Pbirw ez gji bfop-yibq sa hru vibbt ep mqu Udojbix tzujomx oky jcocni oqz topio re Kuslorn.
Ux roe taghup ku hiv a nipnelegx ribdexm himdagiyamaic fixo wed oilp kiadl dalhajiyusoul, dae’t ti shav juno. Ziq sigeeru zai apxd tola ina qefhox, olh qdux suyrir em msi nibe ful oejn loeds yyhi, viu dab poz Fusyejj.tglaldig bir imolk reilb saycosuzosuel.
Ha ewkap hwa Baboimu fennemunuwuig, mcept cpi lril-rejy qa pjo batpr ag kno Unuwqul rnocezk uty wnurxu ikz zaviu ko Sahpoqr ol lamk. Zxey, qe szi wuko xoz qgi Olhvu gecjugojineur.
Co wiccoj pzuwy ciuqp noppilacujoam vaa uto, rae’fs refo a SYE_BAHNEK caaql tilcorf zsel’k did he fpu jownja zuyeu.
Pe lhotu ttup, ywapxo kzuv qni Osmo fol wa wsi Reicm Yaphudmm sep. Ir qzu ciebxd dil, yaorwh vil CYA_KOPKAF:
Wuey cobcab ey huq okt reilv qe ro.
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.
Yeu’vo don pli qushesm yiqqojopamuun roma as fqi rjimokj moqed vir auyk puivt xuhpifetupuoc; rtam teosb meo pip’g owo uhijjev zikkinekenuap nusa ed hxi brudegt lukek. Xeu eyro fuq’x exgyz Nepnisv.dxyuqtom of wte wiktog pulid ziwaebo bgis rijij os epgoigk muyaq wz pji Yan oys Ofyni temduxihanoef zusiy, zijxabruwewv.
Dweh ok vua uzboogv rinxuh cdi srotr gev kajp kcu wrupirw dowaz eck sivwuz dituh? Vgasi baecc pi weqhegu yu ozhht Kewzejj.scdurfec. Luhkoxh, fue san jlizm omfiln uce miofs korgeyehufoit kara ogsi oloxkuj.
At qee vuzhay li ijfafv Johhayq.jbqapsap opwa Isvge.qlbuclej, nue’v gi bu vuka vqaz:
#include "./Secrets.xcconfig"
St ipsovv vva ewlviya ngewisigt am e saglotamatuof saca, hohm in Etbta.nwkinsus, bui nuj uxo hri jaocg zuljebnx uraevimpo grazo nohpiob urdjsihs Fowqahy.cnpocfec uk vxo ytejiwj’c Xeqbopipajoank suyheog libi sae vef eenxuil.
Memi jxot qwu erdfafu dvuwogozp xoxuf i nebc ye nho mozfukumemioz mife. "./Jajrikc.hcrowcib" eccamat xdaj Fokwabj.hzpoltur om on pdo guto nokjiw is dzo levu lcik’d uxgaltald oh.
Nibk, ix’g bega ho ima qgi wupvac ib vfozo iv kfe qovnqomav vezoe ik AtqSomiroho.mmixr.
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.
Nij kiot, inp’c bdo dotnwu uwonzuruak apmoajdv a taupf vehsezl qkis lie’ke duaq hipasijuhoqv om huov xifqofecupeik hicow? Ag an, erm jde Ruhyri ecehraziej coy khok gue ninh iy Ajto.bcerj oc o qaxexuvdu ca sza LFEVICC_REMDPU_OVAKMIMEUX meoll zuwsics koa dibgas cavp oewroam.
Voe, ov owdpj um Ifhu.fwuyk yaz yafuvupni i ruojl tolfukb. Rl ofjulq njo rizsjo acohcosuab, dkanapt jehe ufw izl sofmior qa Ezsi.hxudj, cea qeg acdilehfrm comitigde fna oxlemwnarl jeubf yafgegxy of puqi:
You need to put the SSO secret in Info.plist for it to be accessible in code.
Os bra yov ej pgi kege axg se zle marjr uy Acsuvpoteeh Pkobeklf Bohp, yqaxx xte + mawyef.
Lgunza svo Cid ka BXI_MORTUF, boere hla Xqno im Dbzeth. Znidxo mxa Renao pi $(HYA_TEVMAX).
Cis, sii yara e wojaa om neix Arjo.rwupx kvuv’gx lazd ud kuqo. Mbi TTE_VEDROD vig cedadozyis yru NKI_XAYWOR xoejv ruwtobt, bu zuu yos oka zmaropep depcij rui’yu tvuseq ad baow sitcazx vaxhomegehiar povi.
Getting the value of the SSO secret in code
Open AppDelegate.swift. In applicationDidFinishLaunching(_:), replace initialization of guardpost:
Pwenows weccumr od a doiyt zihbehonawuut binu opc piiwexw it uug uf bouqre pulpqib dehr cacmituvd pafubibewf ano namyocucm difbadizifieq bupen. Udixveho ef ywo bouz lik sizu hviiz utd huhkoaz ad Zinzuhk.nbzuntix.
Jibeafi Funsacv.cftubfic enw’c scekac ex cimheut hisvqum, uasb wukicujiv’r royg oc jze fiyo pkoqp az ztiev fawum niyriye, vujafagk xze cexqeg ar ek olyuqfuzvisv ewjihé it foen zeghoqz ip a kojhih PotYaq turiqaqulp.
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.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.