Authenticate Using Google Sign-In in Capacitor
I have been working on a personal project which I integrated with Capacitor.
The project is backed by Firebase services. As it is in early phase I was trying to get it running with Google Auth first before adding more options down the line.
Not able to find a lightweight plugin, I made my own.
Here’s how you add it in your Capacitor project.
Web
- Install it in via npm in your web app.
npm i --save @codetrix-studio/capacitor-google-auth
npx cap update
2. Add the meta tag for your projects clientId
as you would while integrating Google Auth in any website.
<meta name="google-signin-client_id" content="{your client id here}">
3. Import the plugin so Capacitor can register it.
import "@codetrix-studio/capacitor-google-auth";
4. Use it.
import { Plugins } from '@capacitor/core';
Plugins.GoogleAuth.signIn();
This will return a promise
resolving toGoogleUser
object, which will contain the idToken
at googleUser.authentication.idToken
At this point, you have Google Auth working in Web part of your Capacitor project.
iOS
For iOS, we need to
- Add
GoogleService-info.plist
file to the Xcode project, having theCLIENT_ID
for your iOS project. - Update
Info.plist
to containREVERSED_CLIENT_ID
as a url scheme
Yay, we have it working for iOS!
Android
- Inside your
strings.xml
<resources>
<string name="server_client_id">Your Web Client Key</string>
</resources>
2. Register plugin inside your MainActivity.onCreate
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
add(GoogleAuth.class);
}});
Configure
Provide configuration in root capacitor.config.json
{
"plugins": {
"GoogleAuth": {
"scopes": ["profile", "email"],
"serverClientId": "xxxxxx-xx.apps.googleusercontent.com"
}
}
}