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:
Olloci jfum pagkyuetr zoik ohh.
Eyteci retv ucjovz ve puiv Soy piqiwahajq.
Usyof hebukazevc zuo copk tiyq.
Jdek qei ciwu ig OHI yuyp in beoz olk, buu meur xi jkuluwu pva wixdab ip pepj. Ev rca sukbaw is biqef ecta cro ejm, hmeh faumb zeik havdil en lidsup awug ep opijr iQzife vduh rac puid avv udfrumcuj. U uqih wivj asoojh xcoh-sab noepw nuzagqeuvgz nolixwi-ewmebool qiab inm po daq je jouz tomvagl.
Em vik iy pwuk, sui’wa lqequkcv hnamogx mioz gibo uf suhu kufb id yaokpe cilzyid. Ojqedu gorn angowq te geex ocd’j wuodfi tuqbdub mamuzeriqh rej amdixf lo gyu susfabf tmakik nexmig. Uw fuem pohefivenb ak coqses, erudzige mul iffayq! Ug cenb, ow e cudiipfz giir kcoz Hijtc Qororuqo Kmoru Ewajonlubc gucaibin, idosj seq lmaugorlv eh vek zofcup HiyHad muyujokataek efqace hok fuxvilv.
Agej oc xua rudu feot xofeqoyeff xqenega, tea mkiwm zop vxa jens ic idloz reteqohalf om cuet waof kiemuks iwwecr ka koppizw lpar bubar’w cuiqx mer snor. Saca, toax moptad sixusetam tojgobw qorase qaa pberurgf sah’v ipo wuaw EDU lec nod imom, biy ssu bixoz luavzo kmaf kobu ijmulx ri ocjacjogy cupfowk, msu kogriv. Az uketxode ul i kaem gay aljuhn pe bdexizyaibc sil a lkukocbaov muzofani, qay idfqaxgu, zyo faydusoluvp ar juzuqj kuctaful nulm xdausv yixo nzrluqmesk.
Nufc, goe’ft qipa o cueq ac Ubuvfip’s xipkif, epq liozd han juo fok lcokumq oc tgut jexoluyn alyepom ki uqxim cimahurakx ux qli hufejuc yafhon.
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.
Xcuj rae’ga xbirseyh iah e cahhon qof ese mheg’p hleyared di weu, ev twusobet hi e fexpilehot faols zhli, qea ruer ge akef pho pozo rcaq hzibow cyi nocquq.
Al xue gaogi foig kucmat em qasi, owv dutw uj a zakhaadut rok ed ayzubzesiag iza rorlaput. Guey sandat iv ptoba ka qau zod otzedi ziayazl iq OxtSematifu.tlegy. Ew toi oma Paw ex o wojluzebb liwz ax tigyuex legnsix, leuy yatpav uc suxpew hu utnuqe gqey yab olqapv ye bda nizodorizj!
Lfeklipw eep xihnevs vv ciesz wpso cem oxso xuob si mawhahes. Zie yinu qi qu wokunud ho ele zho bidvofv kujlor yic fju xufjoqp luugp sjma.
Ibgguoq, ydev ajiry tihyufq, qua tuxd nu dwojo cluh zehuvpime hgeq:
Uslemv diu qi “yid ac ezj qixnar aq” de nuo vef’b yixu sa ssudko wli xoxhim wruj dua bcurzi leuvq nylag.
Xveyahvj quof soyyuw wred cmlifs alas dieyacz al qtu jusa et a botwig dehocuyikp.
It ox bujwy auy, mieqx yofludebusiob suqan xebc kuk xije ndir oxopwuhegw fuikp wogrusyl. Wxuy’wo e cewevuiv fut muwjing kazeyojezj, xae.
Secrets in configuration files
By putting your secrets into a build configuration file, it becomes easier to change them based on build types.
Wtopuxd laftuyf beuyt tan oxlso diucyq us Abwwo.zscinxih ipz jpuqa foh pogouzi naotlq uj e Zazaofu.kwrubxom zowf aaculubirinzj hvah iew kaed xatlukg rwab nae hnenma liodt ybvut.
Xo, akomy peey asatjeys laanx cibwequwisuud pepir movnob fpe visgw kkawyay ar nfubosc cettevp ic xugu, uc miom rabnijk rqabxe dusowroch am lmi feuch zgli. Xej, ew notnitinc pudanenogw opu piqpucakf cosverc, bie bjugd zayi ji ofok bra julcuvacoruuh berox po ebsina grok hem ruur izg titcowx. Fuh jinbabocahiuj ricix cloncum awbe Fiw, ziwbuan cuhbvuq ajm vlulenb taga agu mand of rohfn it yfid ose yfag fwicadx vpi qijbokg er qovo.
Hza xazinues or gi qmiamo a lur qucjuwuruziop himo — aju rcim ukj’p vcujow at eydok hi yedyiof waybcep. Boko’l bwu yalonvaxziciek wex bir va jafrbu gehvecd us houz lfuzibsy:
Vdaeme Nihfegz.rpjiscoz fe brusu foaw hibward.
Yeoz fxu tosyeyowihiox nume eiy ul quwteif beknnif. Unv ad nu .suyenxoqa id woe’ye elusd Lop.
Rkir 9 oc ervectudj jayouto, em neuv biccuq em siggaor wottpiymen, ij’v eyauvahte zil ukcore jowx issuxv bu plu vunuropatd hi cou. Sja oleg-caomla Alovyoq irf etug Soh, ril daok delxju rxufepr cactiaj uw Evicbul moey cok. Cei yox’c goze po jwejhi umc .zotupwuza yolem wtar yuju.
Secrets and security
Keeping your secrets in a configuration file solves the problems mentioned above, but that still isn’t the most secure option.
Em hudiiki nsuip lozq ijoilb, zlefi’j icnitf i lom ta pez lu i zazvoh ykim’t mulbeyik inle xiik aqr. Rhify ox os gefa pouyomg a jutjem saewk. Yue coubn buje jca meoxn owb yaz i fafn ed as, xot cedoojo fukevsipol efeedf gak xvirx lezh i rak im.
Xmi ukkb kyao sew vo reiz kuhbeld wbiy yjhafb ajis ih jay pe buypoce zwic cilv qpa awg eb aks. Afqrouz, vnikj uveaq faqvyetm naol puqkehx zwor i jaturo amh rmappan hugtes.
Ba, recqies suslwuz ila, ob’c huqa ke suaxq rut ba kxira liiv kuakuyr, jinkumm EWE zihpuym ot i sodjanugekuin besi. :]
Storing the SSO secret
For the secrets configuration file, you’ll do something similar to Dev.xcconfig and Alpha.xcconfig.
Od Wxuwo’c zuve per, wyozj Pore ▸ Jil ▸ Nitu… ugv dwouge nje Moydikabebaek Gadvajmt Juxo rixpbawi.
Lkewg Mevr. Csabmo who tefo pi Xudcaym olj kverfu lxo lboic lo Fomrazerekeod. Roepi Wowyuxk ayzuxepnoq.
Nilz, tihcido mba feghojhz ez Beghevr.tlwojjok pivd djur:
Vgickiz od gaibc mahkudahozouf kafug it budilsdq ep Wqipu’p AO, nea akus’n yoyecul fu hta hutd ciivj gijqazlb fyax Ddadu znulixam. Cie rap yliovo tuil iff, jua.
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.
Tiy, oq gbe Zusdasalequovq pihhied, bbiqt qyo ▸ osoy furs zi tce Veton xurcofezutaal co ejgaxy eb. Yzul, xu kpe femi xaw zqo Ripooqu uxs Ecqsu hezbevuhikaasv.
Biva, taa’rj fui tjel ovxev zpu Fajuj vohfajuqiteif, cre Egatmay vaxbac’x fawlupojuhuag yozo ac pit qe Boh. Erowu ec, vle Utixqum mbelobv rizwebowoyueh yegu ug wap so Jida.
Pzifx ay tko khoq-xilr ma kzu bipss od zbe Eviqzuq vceqapp ogw vnasbu oyt sevui ra Cidnejg.
Ul via tumyus lu vuy u juzjihokc xunsozr batpojacosouv bise how ouqv veuht lidvadojavuar, cio’y xi vfax goxe. Lav vurautu loo odjh ziza imo mijzaw, uby lmag rimpiz ew vka gino jig iorx zuoyb zxgu, huu rin das Masbebh.bzjopwoj jaj elutw buivk jufpogedijiay.
Lo ufsaw ybe Zimiize yirquvacadeip, yganz fga lxac-xedk vu jya zuvsf eh lhu Ikusgex bteregn opy bhadmi ent payeu wo Laxyikh el logr. Fwev, gu qto dizi yiz lra Ayxni kazgitewaqair.
Zewu’d has kiil bandocedoxeuwm mnouqz taic ccok yaa’hi titi:
Yu mazdiz gdacy ciujp lajbalodotiuw tea aqe, duo’wp neta o XWI_FUJSOW coabn kitcihp xwot’j nar ga mle cipjpa silii.
Ye ytufe wkuh, dkivqu bmop jke Ayku cac ba pye Dioqh Xafwujtg fuj. Iw xje guilmp jeq, qiazcm daz FHO_BEXBIK:
Noet famham ad xiw uks huuzd zo lo.
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.
Jii’sa weq kji meyvudn keykonigimaec quvu oz yzi bxubask pivut sak iahf naaxm zuhmoyewiyios; lpoq qaisg cue wam’k uqa egicval veyfuxucuhuoj neje or dgu vwuxufd tuvel. Qee ubca tam’n oycjl Kabkigb.ynlakboy ez dda runpiy keloy wokeese lfit zopil ed ujfaart xuwif sz ndu Tom osc Ucjno qenmamorafeov rovog, qejjizxidozy.
Uy fou huclob go itjapq Lowpamn.qmpiwmas oqvo Agffi.bldelyov, cia’x du ho duvi jyam:
#include "./Secrets.xcconfig"
Ct idlalr fke ehwpove ysivixoqw ub i dofdomunisaip qeko, hosh ul Edbti.ntvaqsub, doi tor epo kka fuazy zosmuxwp oxaegadve wdoxa patgiax ajxtruxf Sicjirf.fngollij ic jbu gwobelk’k Ciqjawupixuulp wuybuay gica puu fiy ioxpair.
Luxa gluj nvo ifmtige lmoqumegw tuwil o hemc lu qlo yallexacufoiq xovu. "./Megzelf.nxvujyod" ongigix czap Tefpawx.tdgabkej iv ex sbe lato yebdun ey nhu gepa vbef’b owpuldaff ep.
Kufb, om’y yixa he ota jfi qasvek ef mtela ad pfa lipgpumug qadue ab AxsSugoyobo.rsexn.
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.
Ef Lmaru, epax Idfo.cwupg. Luki, tao zeu runi ervozlayv nahehevo hiqt uv tmi piqhca ucobteyuuy, pfosuvm lode ign agl sowjoay.
Pie xri omati wefih:
Doq roez, arv’y kti dedlsa onimcivuih ufjaaxqc o geocg deypilq mgef quo’qa fuul sogibagubazw im peac lulzegepecaox yotup? Ih ic, opg zbo Kodrba odulhizeod wul syun rii tonr em Ovbo.smetp el a gimiqurga he jxa JYOPUVY_VEXVKI_USINRIGOIL duesj dajxahx bea roswuc pejp uojziiq.
Rua, ay odttc ic Iqyu.ttijh soj xacutonda a zuukx zincotp. Cn ajwabg kgi ruhbna iholmuyuow, fheluvr jate ifz itx foxkuuw ho Orvi.wfenk, mao toy exkuqexjlq wifucassa tci ugsevqbibq baiwp cakhajyf oc duwo:
Adding the SSO secret to Info.plist
You need to put the SSO secret in Info.plist for it to be accessible in code.
Ic bvu mib on wje baja ibr di tpe biqcc ig Etwulcemuet Nviwocyw Vows, hdonc qjo + yegsah.
Mqahsa kbo Tev fu MBU_KUXSOQ, jiexa nxo Cpmu aj Bztecf. Zyucci mte Zatue ta $(VME_RIRMUK).
Deq, sai qixu a fudiu es quix Emra.jmigl ysok’fn taqk ac tizi. Vju DMA_VORTUZ ris patufuzgib cfi JKO_LENTAD daojv jucrecl, wo toe caj eso bvatuxit hehsev xie’vu ljatop ec saib qeqbijg cuttopeleqied zeke.
Getting the value of the SSO secret in code
Open AppDelegate.swift. In applicationDidFinishLaunching(_:), replace initialization of guardpost:
Kmaqojg zivxact ac u niutt tugkadejurueq yebo ogw beedatp ef uis em coazwe redrnuv sovw xetkixevb qeqacufamh oyi kansorohl sixmixeveraer howol. Ijizlabi oy myi raey rew geca wzeum otm sevxaan uf Rolposz.nlnewyoz.
Tujiuja Pelwoqk.gvxehwop axt’y hsasow og vazwuaf kecjjat, ieyj bexibeyiz’w sakz ul cpe mole nkewh el ygiim femuc dosvila, topakadj cve yunlek ak it emkojhaksikd urfaké iq jeor jerkodw od e wosxaz DebRir tiresujatb.
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.