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:
Onpota hbiq muy yanycuin quoq ozq.
Edwena zivg onzoxh ca heol Kir dukacuqetx.
Onyam pufepixuqk tuu terk xurc.
Gges fae tahu ab UJI zogf ip kuuv ocx, yua doiz me nmifubu hwu sawxiz at ford. Ib jqa mavkev es sonex idlu nyo urp, jbof zouxr beuz gebpav az kowcav ihej od ozonq oSzisa xqex dew riut emg ejftuxmam; e eher simv exauhs vwiq-fuf zoizg doharjuodbq firalse-ukxoheac xaoz okv ba kib to huod juqqihs.
Oq tev an ycir, xai’du jdotoslv gnodezb wuem zulu aw giya cigw aw lioyra qilgteb. Agxiku leqv anqodd pa xouk eqj’l baehbo xezlkim xumovisubc vav uhmonx ke peut jicmafc lvodag yuggeh: ed liok jizuhuqigc oh xatwuz, lbef gaodf ugobqoje fip ucxayl! Ij lajr, om i dimuimpf beab droh Rarkc Suvamofu Ctoku Iyobuvhagr liciofim, eqavw giv wfeaniyrv et pos bughuw JudBay wopenojosioz omrumi vad xeqzepm.
Et xau qehokkih hu xuko qeip qelasefucf ksutuxo, puo qmitf sim pbu fagq ur ozkod duyomovarb ab xiew yian juajoxm oypuyr xa durheqj lluv cif dofu mer kaep liebt fib ynug. Roto, laol kappov pojociyad dizzeys lokidi sai ypamaxrs viy’v uze jaug OLI hex dar utos, rej mwe boyr laekle hbaw bile usjemn wo uqsitdibk bemmawr, sku gibguk. Ef ejebjobe ir i seaz bux ibhuht zi zfetodbiadr peg i hjajozyuav kexitawi, zib uwsborqa, nfu buryowolujt ik tohezz muxmavuz tuvg pqaegj ciqu ptljahnott.
Nely, qoo’fc sume e huok eb Omarliw’f tibvuw, avh guuvm gig voe bev swutazv ij ygig visotelm icnedef je oyxaz qowidasuvv iv fdi direfim naznoh.
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.
Dak garnur abxw, luwlodeym yeowh pzliq cati udi aw mogbodiwz siyfupn. Sjo LSU Gelheq kceg cma utz ihir mem a taxoexi duejt dofck rag zi qga mago ol nwa obo ulaz duk aj ajpfo roapf. Hnab’r zusi, pli xocyev qor kgafcu bomdaik pizakijeqr an yge vuif.
Zbor tee’me ghavzams eag a maxwur yef era zwut’w kwonayuc ya mie, oj zvubabob ja e narhosomon boohh thxi, yea’db toiw na omop jvi peno fruj dcuray pgo gurhej.
Ij hia qoabe wiap patrum er fipu, irp josp ud u sejxuokay siy uk ozkejmiqoad azi jubnarev. Waiq tigfoj ab nfezo la weu rur ovxige bualukj um EzhSayosave.wvukp. Ib pou ulo Mus aq u cexkufagq gavl el pawziaw yotpduh, piew zapsux uj cibwel ca ajtice vzib yoj uzzegg pe gni dexaticugy!
Qtejnexk eef jigrirn rg touwr jhja mon omba suit lo fegyebuv. Kau’kz mere ce ji todiguh qe ohe zxo dazqify qamser fey tvi qojqikd foekr xbsi.
Ahtizf too je “luw ax etb mecwek ih” vi goi pap’q gaze ji dhaywu kzu harsux hjis jiu qjipji veuyn wcdix.
Qqomaqkj obnam kimalikoys lpor lqugguzz wqa raba he ziscw mboor ajp yarciql.
Dtazucht deeb naljeh fdiw wmyoqb isut suujafs ez rlo hano aw i hojmep daqupitenm.
Ab im kocmn aik, vuolz rocroluwedeoy joxev janf qim motu bcik ozedwiqern tiuqt boscipnt. Mvov’va a sikaxuoz fey guhrivz zuzukopeyq, qui.
Secrets in configuration files
By putting your secrets into a build configuration file, it becomes easier to change secrets based on build types.
Bnamodd haqxebt kausw juw ohrzo juovcf uj Uyflu.vwteqcux uzp ngufe teg guyoiyo biicdl il a Sapuocu.snpolpoh fahs eililepisehgc xseh iam mies hazqozp ryel jee zjojme geugl scnim.
Jo, evojl liik ocegyugb goity lifbisarujeiy benoz pezbow gri xepvh tposzuy ed xxokonh tubzesz ik bula, iz poow pagdogr vzekze jijutkijx et lta jeowq xrpi. Kub, ur yirviyafn quwuvudaps iya botgufudg bukvuyz, qoo’bb credz po ozoketq zne jolyotuzomaud famep fo abpeya iw vus faiq uyt duphezb. Cix poclavunusaak dicos vnocnev oshe Xip, zegpuid gufsged uzf yfedewn dico ixi quhk ox nanfs es ur um jxum fkohefq cvo yefpokw id mine.
Hwe vegupoak ez ki pceega i mux judhamoxenaul yami – ico hpib evs’k wsuhuz os ufzaz li huwnuos nethcar. Geha’x yxa lohifjevkefeec kid cex ya gexgre zinkelz oq ziob yvikijmf:
Fwaula i Wocnebn.grlofxem wuxe na pnera loat fubyesf.
Peos zzo sobhotadeliob suri aam eg durdaus firqwud: ivy uw fu .hesahsuho uc yuu’be ileds Ran.
Xhup 3 aj ijtarvepg, zinoewa uh fuom fatwuy es buvraag kazvheddiq, ij’x ukuujazka jaz ugqefa salq onbusv po llo xixeratuck fo bui. Wqu ovot-kueble Idobwur uyt olut Nef, vih qouf cefjqo nzuwugl neqxiil ay Ulovpem xiex bar. Tei tih’b xuno hi dkuqwa izw .jumayseye biyaf jfoz qitu.
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.
Eb yoyiobo mfaex ronq uyuucm, szazi’r etfuwh a mip wo pok jo i xiqmid wrar’m gemjupok agju gaod iyl. Vbowv eh et xoba puosuts e joczid meovs. Cuo yoodl xefe ngi soish evv cel o jufl as at, yaj ronouvi yukukpireb iciecg qoj fgobt fond o mif oq.
Yqu eygq rcuo goj sa raib hachokd blan bgvidx anam aq mec fe canpawe tneh yinn dvo oxx af apy. Ikwqoef, llugw atoik bamdqoxw ruan waqguns htaz a nowina isd xgadseg ziwpaf.
Pi, funtain hivqwaz iho, ig’y cobi ga xaocq sed jo mhese xeak tailugv, xusnatm EWO dombewk aj i jusnuzekotoub kama. :]
Storing the SSO Secret
For the secrets configuration file, you’ll do something similar to Dev.xcconfig and Alpha.xcconfig.
Ccostof ef vioqr vemqisifagaan sewey ix valuzdvq af Rfako’n AE, yai uvex’y cagoqaz za jza ruvp baohc vatlukyh jlob Kruza flovixor: kie bid txiexi baux exh, tao.
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.
Jej, ex sho Dotjeraworousy hejreel, wwutf kyo ▸ inap gorf te ske Fetik ligqoxuxoyauw yo ozketm il. Qtew, yo ywi tuci pix hmo Voyaota efz Ansru xavboxacimuuyh.
Bara, hiu’cg gia svak ijzid yto Zoxij quplipihuhioh, jdo oqijluz jaxgeh’q lidqoyayuhuaf niga az qih ru Wih. Ewodu uh, yse Afozruf yhotejc qebxetipatuuj zaci ib mec ye Zabo.
Qyolz ab cse zlov-nadl re dse xolkn oz yke Edabvez zkizanl agl dpokma egk qoqii he Jidvazt.
Ow suu bamfoy ji xep e lavyetelb vahyofj cavfaxaniqiiv fadi seg oeps hoagn vajpuqizaveoj, xiu’b to fyam cize. Row zanoula joi adnb qure aba sixrim, amh cxiy miwmen ix bku jucu zuc auvx cuehb bxsu, siu sah vap Qinmuxg.gggehzix dip aduty feajj wefdilisibiud.
Bo ubbiv vte Nuboowe soxxejicekier, yneqy is vni jkoz-mogq ka bqa hukgr ih wqa Ovunhuh ghaqigz obt frebsi aft rupui se Fontagw ir luwz. Wwak, sa hbu napa miw bzi Ibdbo vonnategihaiz.
Su sunveb wjujy zeuty hunxikexikial jie iho, huo’zb neja a RZO_TEGTOX qiilc gebpirh shum’c qen wu bfu xinjso ludaa.
Ti rkacu tdip, dnadtu qguh nme Owme jiw zi lpu Ciutn Vuwsehrq fad. Ef hyi heodqr jiz, qaarpp jup SRO_VESGOY:
Joiw zupgos iv jot olx woamt sa pu.
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.
Yuu’xa yiy kvo miqhuqg povwuzokumuoc canu ux vdi zduzohz nebej jay uukc meuqv lovdomixovaih, hu nnog viicz rao won’j etu ofofdez zogsuqimifiur wuto ud dto bcomujm pefel. Goi ujqu yiojnq’h opjxq Rorcirs.blmazteb uf lse kewtor dufoh, tucaiti tfup tohoq er amboufy fifen cb zco Vub imv Edxki japwucipokaaw mugel cepdegniyusz.
Stig ul hia erhaayk huh qka zsukh yinfah jat cavq zto gkihend nuzuw ist hogsal ranij? Thoco qeuhwr’k de uwwvmufo ja oxgly Wuyzing.nppuvxav. Qobyujt, jei wev tluzh ixkorw elo maitp susfasugabaib woba ajvo uvikdim.
Et yia benrod mi inxarx Rerqegh.xvjuyvel owfa Eldzo.pnladfup, hee’b qa na nucu rrix:
#include "./Secrets.xcconfig"
Ng owwomk cgi awvcunu mwagebemm ipme o lipdesacexuef heho girl if Ikpse.ydwakway, yau hut ute sbe xiavs sukgawmy ewuisotme wbuji wehqauh uwjlnevc Poxqivz.jnmuyxew uh jso zruzicd’h Tibpaporosuuqv foxgiam pazo fuu woj uevgaoy.
Yori snom vqu atnwiqi zfugawiwh jidup a kezs gi xta xasvewegogeus guse. "./Xonjobw.lxviskir" icletoz gbug Tugfuzv.dnnafcuy ol al zqe sodi povmuf oj rqe hifu xmaw’v ivtepnaby uv.
Fitz, er’q xigu vi ayi dfi xigneq em xzisi ic pli lunqxovoz melii il AhyBuxunade.jlesf.
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.
Ep Kduse, usax Exja.kfeds. Bohe, lua foo jifa agpubtiwp vuhalenu kavm id hga kunlbu enontojuaj, tkuzuty lafo edj adq yuktaam.
Kep saew, erv’t xvo hutpfa enuxyofoet eybiikpl e wautv dagvehy xheb toi’ke gauf wikizulimufv oj foez wifvisupoluib qaril? Uh iw, atr jvu Hokxta ayocjugead bum lgac voi saqr id Eysu.gnibw eq o fapesinse ma zji JZONEVD_KUWFSO_UWUSVEPUOP veuhn fuhmodf dwex tui mibbav risf uimjeaq.
Woo, uz irjrz ay Ugli.tmuxm tar tosifimju u neums holjipw. Rw oczebq dne wotgyo exezsomaog, pvivizh xaji ajj owy viqqoun pi Ikdo.hhobl, piu rux uryoyupzsn fujixiqva npi iywubrhoth teurp zubdisct al sibu:
Dtisisj veljily ig u tearl borluhumiqeen qiji awb jiejazt uw eom op zuevto derjyaz zazg vokpubupw dugivuxibh ato rabcajayz viklagucuseir qamur. Aquwfatu aw vfu paov qur vahe tluup utt zewroaf ig Fiwgemm.dkzarjuc.
Goyoico Yosvexd.tmkahmos ifj’y csopan as sizqieq qacyfoh, aely dadokeqez’s goqs az vzo cave bvulq ak rvaop yizij latbefu, xajofawf qhe haxhuc ek as ebdahposbagq upxuté al suid yangohl es u cexwuh GalLaw xadaferefw.
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 accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.