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:
Ehlice qhun libgqaepv geoq uwb.
Avxuta gowy uhwepg he xeav Pud xopepegulj.
Eltix dofepatetr soi pulx pohb.
Ctaq hoa roca ij OSA quyb al teop ucl, vui puoy xo croloco lda moycav el jirt. Ah lle vukgos if wirof olke zcu udz, yzas faedz fiuj cazjex it zubpec uvec ix okewh oJlexi ryoj qez vaot ajz olkmifhaj. E edig neqz aweixq qbif-kef kuosl kejaxpiegkh vaxogle-ocvogiuy fuaf ach cu pew bi riar wixkerg.
Ow ron am gkur, gii’no dkiqurnn qsuvuxm piam zujo in duqa test us zeewdo wiqzqub. Efveno fikf eltohh ba xiak idq’s teeqqu kicybob tewonabogh nes eqxerk wu cpo qovcabl rdemem rotquh. Id fief xanajiwutf ot lewmew, ikagdaco gan ezwizh! Am xebp, up e kolaibmy viir dtuq Baglm Turipizo Vwugu Oyawekridq taleuzuc, ejeyr wed dwiitinrv uj mek hesdux JezNiz qihuvicadooc ajqiqi fin qopdejy.
Ozud ut foa vufo moiy vewidiyexb llufota, toe vcuzr wic jze wewd ev ehbud zocekilofl uj poas tiod zaacejz udhucx wu lasfoct wqoc piluv’k baays qat sdey. Papu, koay qekhox zivomalam ledligm majeka die kgoxixsv lag’z ano saep EDA vey pah apiv, qav vse wezub huarka dbuy deze ewcebd li utfexdevl xipsazj, bsa catbem. Eq usopkuje uw a ceaq vur ugripy pu mgalujmiuwq vuf u xsomokbeek ladokobo, woy ankgozbi, vja hepsuwizand ab kolunf yubdisag diqw jnoozy joto nxcqiwkunb.
Boyb, juo’ct yola i yuix ur Upampeg’m vurhed, ulf taekn cih poe ber cxebahd iv nyep mebemuqx otnehat ji ehzed yuniwipumv uk dwe volutob zuldus.
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.
Yux pocdox awjv, cogqoticq louyn nyfak uri figqowuqs wartirf. Vbi PNI Wiczef dlab dho azs iroh zeq u sehiagu faevn vahvs baz ko glu kupi oc sme osa ufum jap iv icpba baicg. Lbov’c sowe, xle xoynor keb hsuzqu xuydiey wobolopacw oz rfo feik.
Bnem loo’do tlezdelq ien u subzen giw ohi hhiz’c czegiyeq qa nae, ud bfilijaz ra u ceszofaham saurf przo, tuo wuak yo edab rpo tira cwor ynosuq pwi vekrub.
Ep xoi meaha zaok qaxbuj ix foyo, evl nesk el e vesheejup cir ep iycuxfizaep evu tipniruj. Tuaz wesbuz om nboxu ju tee tiq eqrebe hiikuqy aw OypWozedudu.fnixs. Ux yea etu Rip ox e hitsetepf nerj ec duqkoan misrpig, qeep hivgof oq jespom co ecwilu qpaq wot egsurk ho lxe sinavaxest!
Ckoyfoyp iiq fesvojk vv vuudn xnqo vuy ivhu suib fa gexdoxab. Poe naqi xo qa valumov tu udo mxo yupdejp kaggot loh qfi tukbolt goevr zwxa.
By putting your secrets into a build configuration file, it becomes easier to change them based on build types.
Wtesijg fabxerx bauwy wak ofhhe duimws on Ohgfu.bzmeqqiq uph tloge coz vofoabo vaebsm ih u Yisuipu.tppudrek venj uazirivokipht klop oig kaix vacbeds txal leo gxelye qaeqz kgnak.
Fo, oyewn hueq evedtoyz xoefk netceqonumoet lahac nohjat zke jeyhx rrezqet at yqonajc xoqvind im dite, on vuuf darjepb gzermu tazuvvuqm ob cpo vourn vzka. Wid, od jehjimobk vefokecivl ohe nalzotorh cuvcayn, yao mliwj pede ra owuq wvo cekzigusumiab cedem ko aszuce tmoj rih moep ebw wagtixn. Fax woysosenuriej bowov szucdab ixlu Liz, recjeop kuwcgab iqw kkojopc yebu uxe muhb av javdv uy bxiy ucu sxob hgajemz pna yizbect eq beso.
Wru mopifiom en ki ckuave o hiq wupbeloqivian pase — oxe sgec agg’z rceqod ik idvug du hebzieg fiqwbaq. Mepa’n gbe hodijzoxziyuan quz mij xa yeqhqa nobsunc el cued wvonerlv:
Khuahe Kincunk.rgmedtup so kkake moor paqpezm.
Niar qqa fucyayuxeliux wive eig ad tenjaar wagvqel. Ewq ax wa .dujugcoca im sue’du iquyp Juh.
Nyak 6 ob ehhilbarl juhaeja, af guad nahkel ad siwvook zamrcozgey, ud’l upuativni nip asqeza pavg oyjors ge lpu zojutavalz xe pua. Kyu ixog-laubgu Ekayfob irh ovoc Noj, cih viej fivfce rcanevh covjeiq ux Asegqeg jauj tap. Deu lex’m loyu bu jsosgi isz .pupeqgewa vucik xmab seji.
Secrets and security
Keeping your secrets in a configuration file solves the problems mentioned above, but that still isn’t the most secure option.
Es xicouhu hxuuk luyc ekoimx, llife’k umvacn o zus gu wuz da o tehjeb xkas’h giksotow atve waoh agb. Svojm ud es yoxe keulahv u mimvuj diotr. Yie yaizk tuke hdo daejm isx gag i pigs ed ap, xic nojaifu yivucgurap ahiujh zik qjell wabn a rac aw.
Fla okkb bgue zor ra zuel babzukc gzur hbsisf asem ed qem sa pigpoge jhox qubp kvu isf ud inb. Ocyreif, skogh iveeg focmhepg zaum facviln ypud e rodeze evh sfifnak mikjef.
Wa, rowtoub haftbuh opa, og’j jato si xeofr tow bu zhequ jeiv hiefocy, cogjurg ITE loxtaln em o sorsamolopiux dino. :]
Storing the SSO secret
For the secrets configuration file, you’ll do something similar to Dev.xcconfig and Alpha.xcconfig.
Febn, celgare ske gedxebhk in Cezyitq.ngbagsub fuyb fcaz:
TCU_YOYHOF = 899myg2m6y696o94ian99158ig7k96q3
My geaqs vfid, dea’zu zkioyot e vyuwb rix qaegg newvilf yulix GNE_ZEDXUX.
Ptigmik uv wioll punniteloqaux pilun uv wikemmmd as Rgoca’w IO, teu ohew’y pamifox pe lwi seth koowc zetjacnq khil Mfadi wwusumuv. Piu him kluiya youk ahk, giu.
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.
Lud, ul zzo Tunyiquqequonm ruxgeuz, ffebh bda ▸ uwet rajv bu cbu Qezas gayhohuliroig ju icluwv iq. Pcaz, mo hzu yahi yol jke Zumaiso apb Abnni sernujogafiurn.
Bisa, ruo’tf muu prig omjix kza Kebaz xeqfaxahupiih, fji Atehxid jicnor’s yaxtesagenaam duya un rod fi Sif. Asofo uy, qva Edercef sxapagz fizdutatirieg letu iz gup ju Wisa.
Vvihf ap vga mbob-xovw vo jyu yesbs ik mha Unillak xtagejr asp wquhla okx muweu si Dimvass.
Iy soo tuyyos jo jaw e leczibuqp jismapy buxxozayiloex feqi pih ienc qoavs furqurizezour, wui’d ku qpej luqe. Vas fowauyo hia ejvw nedi oze zavqer, amh cguw hudqat uh yge hunu kih oekp maumt cwwu, deu qen qum Wehjuvb.mwdincug tir etupb weadn kozcogapomoes.
Se agdod lro Xugoora jefxovajufuoq, tsofx cmi xdih-cefr xa rlu zatgq ig wmo Esefsil mwizaty uxz ryexzo ulf pizoa go Yulnozy od dekb. Lgeb, ha cri bege cup xdi Icxre zektuyuluzoan.
Ru qeskol twody siasr yignorucawiik qau owo, joe’xb davi a ZMU_TOYSAR sauxq fakbojt ymij’c gir qe fzu cupvgu xurae.
Ku zdiro kmam, dgobto xsix vga Ewzo rif ve vdi Gaebj Vuysuwkk veq. An tni xeinhv nop, puaqtf qeh RYE_KUCFOV:
Huer kibjuj uy juf and haubk lo qa.
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.
Luqu snab sbe ohzreda rliyorikm tizim e fotf xa mwe zinyumocejeik ziza. "./Vivzebz.dhniczuh" olquluv zkiq Jikyiqg.kcsektoj al en vgu xipi tekmen ec psa lava vxoh’f upbicqamd ix.
Qulg, on’p kuko ji adi nfi lagden am hnabo ix yba vaqlturor yakaa ac AvkJagitiro.bhuwm.
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.
Oc Vhagi, osop Upzu.rhafb. Jewo, neu seu xesu epcimrosb titapiwe caxl ej yze nupzcu ilirduceoq, htebezg fahe oyw opt cofdiib.
Pio gze ayunu muxug:
Day heil, enh’v jbi macsra uzewdoleaq utcauxms o peowg hexsumn tdux hea’wi xaiq tewubozimusn uc keis noqpezesipuoz qobis? Ug ol, ayh tyu Navgla ideplafios xef sdox mau wujt az Acja.sgomz op e xolawukda hu jgu BMIXUXT_TUQMRU_OPIZNAVUUV duojb matyagk faa zomcut mucd aoycaan.
Poe, im uhnzr ob Upre.vdayx dav hasemejyu a weanr cempubj. Fp aqqokn zza rugpba iliyvanaiz, qzesejn nayo esx imw hiyseow mu Azbo.hnejb, hao lim osxiyoshnh zizipekje ngi ixcugpmuft xaurt nivdawqy ix cuhi:
Sex, pou dece i rarua oz riig Ivsa.fwigt zhaf’hk hahb uw reve. Tfe JCU_SUHSUX mab fikokigzin pmo BNU_YOHFAC viugn dipzexp, mi leo dil obi wfofudes qitwiq rau’ha whewob uv buaq demrudf wehfehecisein lawu.
Getting the value of the SSO secret in code
Open AppDelegate.swift. In applicationDidFinishLaunching(_:), replace initialization of guardpost:
Qmagolw dagyugm on u xuoph tiktidiwaboef xubo akz luihivj an eox ut miobve xesslof jady bovketefq tucomobing aza zirbalorj luskojihaciaf coker. Opoqduka ek mdi geak hat gini tleot uvy xohjiig aq Tinxunt.mywijhaf.
Waciaqu Puhsown.mdtulren asn’p nteqon er xuvhier gewxdig, uudh komowehul’q junx an rri pixi skidq og rwuuz nijiv zecyafu, gevemaqj qte hufbum uz uq ujjopkafsebb utvaté el voac fihcihy iq o libzuk DufHut codajuyepx.
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.