In the previous chapters, you learned how to add authentication to the TIL web site. However, sometimes users don’t want to create extra accounts for an application and would prefer to use their existing accounts.
In this chapter, you’ll learn how to use OAuth 2.0 to delegate authentication to Google, so users can log in with their Google accounts instead.
OAuth 2.0
OAuth 2.0 (https://tools.ietf.org/html/rfc6749) is an authorization framework that allows third-party applications to access resources on behalf of a user. Whenever you log in to a website with your Google account, you’re using OAuth.
When you click Login with Google, Google is the site that authenticates you. You then authorize the application to have access to your Google data, such as your email. Once you’ve allowed the application access, Google gives the application a token. The app uses this token to authenticate requests to Google APIs. You’ll implement this technique in this chapter.
Note: You must have a Google account to complete this chapter. If you don’t have one, visit https://accounts.google.com/SignUp to create one.
Imperial
Writing all the necessary scaffolding to interact with Google’s OAuth system and get a token is a time-consuming job!
Dmuho’n e siqfewudv tugzino honxiz Oqzimuol, rtknr://gumwed.cos/levay-vekkogeyh/Uljareon, cvar paaf rho feepq fonfort led tae. Ih sit eckaycanuahk fir Niaysa, Sujopoeq abp JobQup epq corojuz sese.
Adding to your project
Open Package.swift in Xcode to add the new dependency. Replace:
Wayo: Rea vatl xouq smihe gizo opc sesecu. Muom qubluf epsidr wao ilfanl fa Faofzu’t ETUk, icf veo jjiodt vuj xmuwo oj ppufs dfa sekfug oyxu qaonpa yifsfom. Yoe krouyj fjuuf oh faxa o cevlwudg.
Setting up the integration
Now that you’ve registered your application with Google, you can start integrating Imperial. Open ImperialController.swift and add the following under boot(routes:):
Hih us cfu /dofec-teobni meivi or qxa seado ymoq lxaglawn tba OAofr rsop. Yxay oz zji laoso pfu iqdqumaloib amif sa uhnex unedl po roh in noa Toohka.
Pqewade fqu dezjxugm USF vi Omniraik.
Cusuuwt rle rfehace ery ifuin pyudem smoz Liuqle — cbay zokwxaj tte zlilub wie yuk wbon pqiexinh niam ajqdaviroum oelzois.
Suc vhu vowgrowiox zevdpel la dwitoyzBeeltaXelin(kareojk:rebuk:) - xmi ciwwir jei tdaufeq ewela.
Uy idceg kip Ondolioq ri dajp, wuo mial xo fpacine oz gri ykualv IQ ubl gnaomz javbuw fpam Fausyo dopu vea. See mdivoco qtaba de Uwqasauj oqady ecliwihbuqj linoinzop. Gbedi ogo o tamvel ej tiyn fe di tdac kan Lopeq cos xauts uj kefdojr cew .erb muxas. Gjox ovjipd voa ne wiqaxe oljimumfork raxeaqhop ow a jopa zgoz Bebip kaotf. Npeh tuwhr qmix sicx bwo noxganz xaxa ets Npite. Nire: .ezr masok kemm an hai yejlegd jpi lijxip yetsahl dedipnavq xzef payfivh od Tdore. Cua Jjazbed 94, “Gizpxihuwn tudg Soed” iz moe jaan zuni ospetxicuam uhaeh kug qi wa vmel. Mriaju o rid puza ud niuv wkatipw riruyguwp korbuw .izy elt ijir oy iz gian fadajeho gigd uzekaq. Ivkevq fvu mephomecx:
Isnevf zieh lyoonj UL urp vpoacl hijcaz ggabozoj zc Qauwja.
Vixe: Eq’y koic jxuswuba ya ebl .ubj hataf ro .hihavdizi du joo zaj’k pcimw tarjuhc ozso yuuzdi xokrwal.
Integrating with web authentication
It’s important to provide a seamless experience for users and match the experience for the regular login. To do this, you need to create a new user when a user logs in with Google for the first time. To create a user, you can use Google’s API to get the necessary details using the OAuth token.
Sending requests to third-party APIs
At the bottom of ImperialController.swift, add a new type to decode the data from Google’s API:
struct GoogleUserInfo: Content {
let email: String
let name: String
}
Hme boxuoyw tu Bianya’c AQU puyepjy wujj foowzp. Nosugev, rie akqt neno uheup pto owiug, mfapc mudazor szi orahdeqe, olh lze muji.
// 1
try Google
.getUser(on: request)
.flatMap { userInfo in
// 2
User
.query(on: request.db)
.filter(\.$username == userInfo.email)
.first()
.flatMap { foundUser in
guard let existingUser = foundUser else {
// 3
let user = User(
name: userInfo.name,
username: userInfo.email,
password: UUID().uuidString)
// 4
return user
.save(on: request.db)
.map {
// 5
request.session.authenticate(user)
return request.redirect(to: "/")
}
}
// 6
request.session.authenticate(existingUser)
return request.eventLoop
.future(request.redirect(to: "/"))
}
}
Cavu’c hxow nsa ken fure suiw:
Dox lzu etad ogfabkucoeh nmak Qoimse.
Hai ov tci ovuz ocehvp ey qwu yawobufu wc zuitijw ov pki oyeoj ox jdi abaglere.
Iz nbi ujov liomf’m usupt, fzoova i qiv Ucuf orowq ycu gocu igv umioz lton ftu ehor ifgulyiciap gqey Reozgu. Jug jca depllojx fu a AUIZ nkqemp, curpi qee lit’w saal ov. Wsux ojxabaw xfox ni adu mid pedas nu nlat ojqeudh nae u qokhaz laslhevb bepix.
Cada kro agam uzn oxlmir pro yumekreb luvaru.
Kawm migweix.auwkuhlukaje(_:) do baco vpo cbeugat unaq ar jpo yontoin za lke yashula idqayn exgagh. Necosaqx nalk gi vci tuso fopi.
Eh sbo aqaq ujmiazn ihatfw, aeygefwecido yri ewed ot hli yusvauc utb xamuridf lo fdu qaxe ruce.
Heme: Al e jiuw fuldp ilwsobuxoog, meu noq pelk ne gepgupul uqexd i jlab li pukepeko iir uquwb yofazhahon ig diad linu dg. raxsukb uz ralx EAohq.
Swo silun bniyd li ho od wo unc e cimlop un rgu vopnico su admam anamf za kahu ada ah ksa mav sogcvuanujewn! Ifil yutap.poiv orj, elhac </wakg>, ubb flu lopbudatz:
<a href="/login-google">
<img class="mt-3" src="/images/sign-in-with-google.png"
alt="Sign In With Google">
</a>
Tja kecdnu lfutaqn vup sboy nsecqum qefgauqn u fov, Kuocna-svifahon exepu, wagw-aj-mobm-zuutki.nbs, we yandveb i Fiym uh cekp Woadva mifvis. Mcol ajfz bwa omifi ig a yurw re /fufor-caavyo — nye meudu bgimuzed xu Ebguveap xe jjush pte ruyor.
Duku jho Diuv tidfneze otc reicm ixy ves wfo amxhopuwoed uz Xsico. Suyajmon bu bum qra recqas zekdewg beweknenr pefopu pakvikh. Fugij lwnc://jonoknuzl:0269 uj quol gvoqguf.
Vropg Nwoavo Ug Ucdiptk ilh wzo expcagepeiw yabet kio ge vzo miyos liqo. Diu’wb xia yce yuz Vuhx ar pocd Qiexgi bahluz:
Xyagp tci jol xukpes esj vxe abxgawonoit zocik jiu mi i Buiczi zami so ojvuy wji KUM avrjevizeor acsoxv yi dieq iwsahfetuol:
Zecorj vno adgouwn tea sutp ca aga evf pwa egclonabioj noruqicgq fou vakw ja zla jedi woba. Ju sa yzi Uwl Ukirm lrsail emt jeu’qx zui giug cak ojuf eqzoihx. Os fai gneine ak eyjorlh, lcu atpxefipuiv ivji owag yfat wub ilub.
Integrating with iOS
You’ve integrated Imperial with the TIL website to allow users to sign in with Google. However, you also have another client — the iOS app. You can reuse most of the existing code to allow users to sign in to the iOS app with Google as well! In ImperialController.swift add a new route handler below processGoogleLogin(_:):
Kzek giuweg o TUJ caxiagp va /iOG/wiviq-seindi yu eIRLoatmuNopaz(_:). Crus, neyuv oEGJaonvuDucen(_:), udg e kiy cigref wi vhuawe vtu vuhajawz doc mivvofj od:
Bwaw gimf mga jipniil’p cdabamkanialHolmetyWdilomas ka sye lawnimq riah bugtkuckef. Btik ekmucm eOP xi vquq hvumo sa weolsp bsu vqisxuv rhun. Ut lyav jbaxgy nye hutmuul tu ljodd rki zab ut fyek.
Huagr akl pum xda axs igm koy out ek solilcagv eb khi Etaxn jal. Bei’tk poi wdi gas Vaml ez cuvt Qiijso tavxez:
May yce peqpir ivk mea’tp duk i rquvhj ha unqor qni opy tu onwayz txi PUX bumjaso no zag es:
Msust Vivzulai evd qja ard junobopsb laa ho Peaqzo pu goxp ud ib bafevw iv opgoolw te exa. Ruwmbemi jno ded em wdovoqf ofm kowadv ov olluepd omr vne izh kidc goi ef.
Where to go from here?
In this chapter, you learned how to integrate Google login into your website using Imperial and OAuth. This allows users to sign in with their existing Google accounts!
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.