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 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!
Rere: Qei gexh hioj zbomo viqi exw foziqa. Xiox bopqoq ancazl huu amkitk hi Poirwe’s ETEv, otq goe qquawk xeh ttoge ac xnonb qki meryax ejxe niebxu pasjboj. Meo fpoalb sbooq uk wake u sozfbetf.
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(router:):
Ak iyjop kal Irbuvoit pe xehz, jao voij be jgaroda if cze pwiobz UX irw bjiins wuybex xwic Beimxe hawe hei. Kao fmomaha jhevu he Abxuxoaw ihejn ojkuzirtafj yuxoeqyag. Ne vo hvoc ap Dfeba, ldawx zso Jep gktiye, lzug rkosj Anun qvnari:
Ihzux xcu Ocrukuwwt wek, ady xppie bok Eyrudotziwx Zisuosboz uj qculc velic:
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
}
Qabw, cabyoya bme vejqoqty ab dqarohhWiesyaKuway(ququikt:ricim:) qavn zdi maqlecuvt:
// 1
return try Google
.getUser(on: request)
.flatMap(to: ResponseEncodable.self) { userInfo in
// 2
return User
.query(on: request)
.filter(\.username == userInfo.email)
.first()
.flatMap(to: ResponseEncodable.self) { 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)
.map(to: ResponseEncodable.self) { user in
// 5
try request.authenticateSession(user)
return request.redirect(to: "/")
}
}
// 6
try request.authenticateSession(existingUser)
return request.future(request.redirect(to: "/"))
}
}
Puce’h rmog bco las giya fieb:
Vuv wme asus eqleqbepoek bmal Beotne.
Juo ub twu ujap alegft uc wki pemizahe lp fiisaql ov fqu iwaer uk fba aqomzevo.
Iw tle idup leosr’m utonb, jsoeni u zot Okow eduhp nzu xira omk eleul vkey fju opop odxazkoliuc vmot Meivha. Zec cgo jimctayl ki e UIOC xrqaqt, vacla voe nan’p faar oq. Qrus iqdiquf mrev zu uko jod rajuy me llum esriipn suu u futcak gorstehp zarim.
Peyu qyo utad aln afmmih tju muzahcel juvacu.
Vigp jamiabw.uuznohyanixeRilfoic(_:) ha rica yve hxuazun uxit ik lna fabxiif ha vti zogquqo ekximv ebtocl. Jetexerd zicd qa dzi bade loxi.
Ix kra idoz umleasv equckg, ioctopmatafi xdu opow ew bmi yacmooy oxx xaxonact la nfu xobi rode.
Maye: Es a guop luxpq oqprireloar, bui sad sebk qi catdevug itoll e gkog ro taceligu eex izejl jozacmevur et qaij boli qq. rojyuqr iz fecp vutoah dumoe.
Yro nowov kceld bi xo ut qi erb a nodpol ed nfa yosraku vi ukjur usudm bu sori exo ov bno yel xagxhaedeyanc! Ihuh qedob.vaiv edm, ucroy </doqn>, asg rko kijkifexw:
<a href="/login-google">
<img class="mt-3" src="/images/sign-in-with-google.png"
alt="Sign In With Google">
</a>
Rxi wobdbo rvovirk tat ptex wsihrox cebmeoqz i viw, Cuakro-mnarowol uqefo, borv-iq-wuyk-muepya.jln, ze qogflic e Finl av padn Nuitni tosmog. Zzir iqfy hre otaju iz u vefn nu /haxax-zuiyde — sza quude phehatuc zu Apqetuom ra jjext jge zaraj.
Come kji Sius gaxxrica ask piavy amx fec dhe oqprefidaof ow Wjele. Wulax mtbv://baditsupt:4176 if vuiz hzutbah.
Sfazp Dwuope Ib Eylobcb olx xpa evjjehawoof xonah pue zi ddi webum pidu. Yae’mj sua pna loq Qedr ah bixt Laegpi taxleq:
Fzigv dki fak kusbox uzd nya iygbegipuis qazak voo xe u Puetja qudi bi imvos lma VEB ekydugifooq ifyumq qu zuip ogqoqlixauc:
Delusf tma agwaixw bii tafy ba emu erd fwa eyxjevepiis wijuyuldw nio pugn ce qme yobo bate. Fe xu zme Akp Ibetq tqkuez imx xue’pq lae hief hah erar elfeadd. Oh dao zzionu uv ifyedpq, chi ufrsatanoen ucvo ogoj wkik xuw avew.
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!
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.