Google Authentication with MongoDB Stitch — Swift 5
One of my favorite capabilities of MongoDB is being able to use social login. When I first started learning to use the cloud server, I already wrapped my mind on using Firebase because I assumed the Authentication methods would be bogus — to my surprise, I realized I could login with Google, Facebook, & even Apple!
For this tutorial, we’ll be learning how to login to Stitch using your Google account.
When a user logs in, Google provides Stitch with an OAuth 2.0 access token for the user. Stitch then uses the token to establish the user and access approved data from Google APIs on their behalf.
Here’s what we’ll be doing:
- Creating an OAuth Client ID
- Enabling Google Sign-In in your Stitch App
- Write some Swift code
You can clone or download the template from GitHub: https://github.com/danielkioko/MongoDB_GoogleAuthentication
Before we start, make sure to install these dependencies with CocoaPods. Navigate to your iOS project folder in Terminal, run ‘pod init’, run ‘open podfile’ paste the following on a new line after useframeworks!
pod 'GoogleSignIn'
pod 'StitchSDK', '~> 6.1.0'
Creating an OAuth Client ID
We’ll need to go to the Developer Console to create a new credential for a Client ID. In the drop down select iOS of-course, then you’ll next have to provide a Name & your app’s bundle identifier.
The App Store & Team ID fields are optional. Once you’re done, download the ‘plist’ file and place it inside your Xcode project folder.
Another thing we should do is to set up a URL type to handle the callback. In your Xcode project’s ‘Info.plist’, under the URL Types section, find the URL Schemes box containing the string YOUR_REVERSED_CLIENT_ID
. Replace this string with your reversed client ID. It looks similar to this:
Enabling Google Sign-In in your Stitch App
Head to your Stitch app in MongoDB. On the side menu, click Users, then Providers & click edit on the Google option.
Paste your Client ID, select or create a new secret if you don’t have one yet & finally select the Metadata fields you’ll need — This is the user’s information that Stitch can access from Google.
Writing some code
Open AppDelegate.Swift and type the following for configuring google sign-in with your Client ID, then we’ll send the token to stitch.
In ViewController.Swift, let’s write the function for signing in.
Then finally, let’s prepare our screen on Storyboard. Make sure to link the Button with the action we wrote on the ViewController!
Thats it! We’re finally done. Run your app and check what prints in the console.
Template link on GitHub: https://github.com/danielkioko/MongoDB_GoogleAuthentication
Feel free to let me know how it goes in the comment section.
Happy Coding! 🌟