Capacitor Firebase Authentication Plugin
Capacitor plugin for Firebase Authentication that handle the authentication on Native layer and propagate the token to the web view layer. After the sign-in process completes, the user will be signed in within both tiers.
The plugin supports Google, Twitter, Facebook, Apple and Phone providers in Android, iOS and Web.
| Platform | Google | Facebook | Twitter | Phone | Apple | Email/Pass | |:-----------|:----------:|:---------:|:---------:|:---------:|:---------:|:----------:| | Android | ✅ | ✅ | ✅ | ✅ | 🚧 | 🧠 | | iOS | ✅ | ✅ | ✅ | ✅ | ✅ | 🧠 | | Web | ✅ | ✅ | ✅ | 🧠 | 🧠 | 🧠 |
✅ - Ready
🚧 - Work in progress
🧠 - Thinking about, date to be defined
Requires Capacitor Framework v2.2.1 or newer. This is another episode of the Capacitor Framework braking changes on Android platform (com.getcapacitor.Config, now com.getcapacitor.CapConfig).
Really sorry about braking changes in minor release, but I want to follow major version of the Capacitor Framework.
You need to use version 2.2.0 of the Capacitor Framework due braking changes on Android platform (com.getcapacitor.Config)
Sorry about that, but there is no path to do it, I my case, me and my team decided to re-build the projects from scratch, this does not mean code rewrite, just a project, configurations and build. The good news is, there is no change on Typescript/Javascript/Java/Swift facades.
Anyway, you can make a try with Capacitor Framework update instructions: From <= 1.5.1 to 2.0.0
The firebase import was changed using
esModuleInterop, that was a Stencil requirements, please see issue #38.
1 import firebase from 'firebase/app'; ~~~~~~~~ 8601 export = firebase; ~~~~~~~~~~~~~~~~~~ This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.
If you see the message above, please use
esModuleInterop=truein your
tsconfig.jsonfile.
Required GoogleSignIn 5.0.0 on iOS platform, run
pod updateif using lower version.
Should we do this? It's very simple to authenticate on WebView without any plugin. For awhile, waiting a good reason to do it. (track interest on Issue #24)
Install the plugin into your Capacitor project with npm.
npm install --save capacitor-firebase-auth
Don't forget to run
npx cap synconce after the installation to propagate the plugin to native projects.
capacitor.config.jsonconfig the providers list, language code and native authentication as desired
[...] "plugins": { "CapacitorFirebaseAuth": { "providers": ["google.com", "twitter.com", "facebook.com", "phone"], "languageCode": "en", "nativeAuth": false, "properties": { "google": { "hostedDomain": "my-custom-domain.com" } }, "permissions": { "google": ["profile", "https://www.googleapis.com/auth/drive", ...] } } } [...]> Note:
nativeAuthis a feature supported for Google, Twitter and Facebook (not Phone or Apple) to sign the user on the native layer too. >> This is useful if you need to handle any feature provided by another plugin that needs authentication.
Note 2: Don't forget to remove
hosted domainproperties from Google SignIn in case you don't need it. See more here about this feature.
In file
android/app/src/main/java/.../MainActivity.javaadd the reference to the Capacitor Firebase Auth plugin inside the Bridge initialization.
[...] import com.baumblatt.capacitor.firebase.auth.CapacitorFirebaseAuth; // Initializes the Bridge this.init(savedInstanceState, new ArrayList>() {{ // Additional plugins you've installed go here // Ex: add(TotallyAwesomePlugin.class); add(CapacitorFirebaseAuth.class); }}); [...]
For Typescript users, please, review your
tsconfig.jsonand ensure that you are using
esModuleInterop=true.
Please, don't forgot your Google Service .json or .plist file or your app will crash on the startup.
Add the pods that you want to install. You can include a Pod in your Podfile like this:
target 'App' do capacitor_pods # Add your Pods here pod 'Firebase/Core' pod 'Firebase/Auth' end
URL schemefor your reversed client ID. To find this value, open the
GoogleService-Info.plistconfiguration file, and look for the
REVERSED_CLIENT_IDkey. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
Since that Apple using Push Notification service (APNs). You need to have
.p8key and upload to project FCM config to use phone login or you will get this Error. Do so from the Settings page of the Firebase console. See Configuring APNs with FCM for details on how to get your app's P8 key.
implementation 'com.facebook.android:facebook-android-sdk:5.15.3'
android/app/src/main/AndroidManifest.xml, add the following XML elements under :
android/app/src/main/res/values/ids.xmladd the following lines :
xml [APP_ID] fb[APP_ID]://authorize> Don't forget to replace
[APP_ID]by your Facebook App ID.
Add your your
[APP_ID]and
[APP_NAME]keys in the file
ios/App/App/Info.plist.
[...] FacebookAppID [APP_ID] FacebookDisplayName [APP_NAME] [...]
Add custom URL schemes to your Xcode project:
URLscheme for the Callback URL of Facebook Kit for iOS. In URL Schemes box on the configuration page use
fb[APP_ID]. Leave the other fields blank.
Add the pods that you want to install. You can include a Pod in your Podfile like this:
target 'App' do capacitor_pods # Add your Pods here pod 'Firebase/Core' pod 'Firebase/Auth' pod 'FBSDKCoreKit' pod 'FBSDKLoginKit' end
Dispatch the designated callback URL to Facebook Kit in your
ios/App/App/AppDelegate.swiftfile.
Facebook SDK ``` import FBSDKCoreKit
...
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // Called when the app was launched with a url. Feel free to add additional processing here, // but if you want the App API to support tracking app url opens, make sure to keep this call
if let scheme = url.scheme, let host = url.host { if scheme == "fb\(String(describing: Settings.appID))" && host == "authorize" { return ApplicationDelegate.shared.application(app, open: url, options: options) } }return CAPBridge.handleOpenUrl(url, options)
} ```
Don't forget to replace
[APP_ID]and[APP_NAME]by your Facebook App ID and App Name respectively.
Follow carefully sections: Before you begin, Join the Apple Developer Program and Configure Sign In with Apple of Firebase docs.
Enable Apple as a sign-in provider, in the Firebase console, open the Auth section. On the Sign in method tab, enable the Apple provider. If you are only using Sign In with Apple in an iOS app, you can leave the Service ID, Apple Team ID, private key and key ID fields empty.
No additional configurations are required by this plugin.
Don't forget to enable
Apple Sign Incapability for your App on Xcode.
import {User} from 'firebase/app' import {cfaSignIn} from 'capacitor-firebase-auth';cfaSignIn('google.com').subscribe( (user: User) => console.log(user.displayName); )
import {cfaSignIn, mapUserToUserInfo} from 'capacitor-firebase-auth'; import {UserInfo} from 'firebase/app';cfaSignIn('google.com').pipe( mapUserToUserInfo(), ).subscribe( (user: UserInfo) => console.log(user.displayName) )
import {cfaSignOut} from 'capacitor-firebase-auth';//[...]
cfaSignOut().subscribe()
import {cfaSignIn} from 'capacitor-firebase-auth';cfaSignIn('phone', {phone: +16505551234}).subscribe( user => console.log(user.phoneNumber) )
On iOS platform the observable will complete without emit (like EMPTY), follow the notifications below to sign on Firebase on Web Layer.
import {cfaSignInPhoneOnCodeSent, cfaSignInPhoneOnCodeReceived} from 'capacitor-firebase-auth';//[...]
// Android and iOS cfaSignInPhoneOnCodeSent().subscribe( verificationId => console.log(verificationId) )
// Android Only cfaSignInPhoneOnCodeReceived().subscribe( (event: {verificationId: string, verificationCode: string}) => console.log(
${event.verificationId}:${event.verificationCode}
) )
Suggestion for web authentication code to iOS, the
verificationCode`` must be provided by the user, please see [Firebase documentation](https://firebase.google.com/docs/auth/web/phone-auth#sign-in-the-user-with-the-verification-code) for better options.typescript
import * as firebase from 'firebase/app'; import 'firebase/auth';
const credential = firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);
firebase.auth().signInWithCredential(credential); ```
This implementations of the javascript facade calls, return in addition to the Firebase user the information returned by the plugin from the native layer. For example, in Twitter sign in the token and secret are returned for use with Twitter User API.
Specials thanks for @go-u, by this suggested improvement, more information please see issue #23!
import * as firebase from 'firebase/app'; import {cfaSignIn, SignInResult} from 'capacitor-firebase-auth/alternative'; import {SignInResult} from './definitions';cfaSignIn('twitter.com').subscribe( ({userCredential, result}: {userCredential: firebase.auth.UserCredential, result: SignInResult}) => { console.log(userCredential.user.displayName); console.log(result) // will print (providerId, idToken and secret) } )
import * as firebase from 'firebase/app'; import {cfaSignInTwitter, TwitterSignInResult} from 'capacitor-firebase-auth/alternative'; import {SignInResult} from './definitions';cfaSignInTwitter().subscribe( ({userCredential, result}: {userCredential: firebase.auth.UserCredential, result: TwitterSignInResult}) => { console.log(userCredential.user.displayName); console.log(result.idToken) } )
import {UserInfo} from 'firebase/app'; import {cfaSignInTwitter, TwitterSignInResult, mapUserCredentialToUserInfo} from 'capacitor-firebase-auth/alternative'; import {tap} from 'rxjs/operators';cfaSignInTwitter().pipe( tap(({result}:{result: TwitterSignInResult}) => console.log(result.idToken)), mapUserCredentialToUserInfo(), ).subscribe( (user: UserInfo) => console.log(user.displayName) )
The user will be signed in only in web layer. This limitation is due to the verification code only works once. So, there is no way to authenticate the user in both layers (native and web) with just one SMS Code.
If you feel that project is useful, please, considered to buy me a beer through PayPal
Looking forward to enable FUNDING.yml soon.
JavaVersion.VERSION_1_8because the plugin does not use Twitter Toolkit anymore.
nativeAuthfeature on readme file.
On Code Sentand
On Code Receivedfrom Phone Verification process for Android Platform.
On Code Sentfrom Phone Verification process for iOS Platform (The Firebase does not read the SMS on iOS platform, so there is no way to notify
On Code Received).