Facebook login with Ionic is still one of the most requested articles, and the good news for you is: It’s not that hard at all!
In this Quick Win we will allow our user to login with his Facebook account, and after we are authenticated we make a request to grab some user information from his Facebook profile. We will have to create a new Facebook app and connect our Ionic app to that app, but you will see it takes us only a few minutes to get a result like below.
Note: This is the iOS behaviour and seems to be standard on that platform for some reasons. On Android, your Facebook app should open directly without those additional clicks!
Setting up a Facebook App
Before we start with our Ionic app we need a Facebook app, so go to the developer page and create a new app.
Once your app is created you need to add the iOS and Android platform. Therefore, navigate to Settings and hit + Add Platform. After adding both platforms it should look like this:
Notice that I already added an iOS Bundle ID and Android Google Play Package Name?
This is the next step for you, because your fields are still empty!
This is the same ID that our app has inside the config.xml file, so if you already have an app add the Id to those fields.
Otherwise, let’s create our app first and install the Facebook plugin from Ionic Native.
At this point you also need the App ID of your Facebook app as well as the name ecause they must be passed to the Cordova plugin as you can see in the statement:
1 2 3 4 |
ionic start fbLogin blank cd fbLogin ionic cordova plugin add cordova-plugin-facebook4 --variable APP_ID="YOURID" --variable APP_NAME="YOURAPPNAME" npm install --save @ionic-native/facebook |
If you started a new app like me, you still need to make sure that your config.xml id and the ids for iOS and Android inside your Facebook app are the same. In my case this looked like this:
1 |
<widget id="com.devdactic.academytest" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> |
Your bundle id is always your reverse domain or team name, and this is also needed when you submit your iOS or ANdroid apps later.
Now we just need to make sure that our Facebook plugin is loaded by adding it to the src/app/app.moduel.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { Facebook } from '@ionic-native/facebook'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, Facebook ] }) export class AppModule {} |
That’s all for the preparation. Actually it’s really just about creating the Facebook app, adding it with the right values to our app and adding the Platforms to the Facebook app with our id.
Simple, right?
Implementing Facebook Login
Actually the hard part is already over, now we are almost done. Inside our view we only display a button in the beginning to start our Facebook login, and once the user is logged in we display some more personal data below including the user image!
Go ahead and change your src/pages/home/home.html to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<ion-header> <ion-navbar> <ion-title> FB Login </ion-title> </ion-navbar> </ion-header> <ion-content padding> <button ion-button full (click)="loginWithFB()">Login!</button> <ion-card *ngIf="userData"> <ion-card-header>{{ userData.username }}</ion-card-header> <img [src]="userData.picture" /> <ion-card-content> <p>Email: {{ userData.email }}</p> <p>First Name: {{ userData.first_name }}</p> </ion-card-content> </ion-card> </ion-content> |
As we have set up all before, the login with Facebook functionality is now only one line. Also, we can pass into this call which information from the user profile we want to access, in this case it is email and public_profile. Therefore, once we log in Facebook will ask for those permissions like in the image below.
Once we got the login token we could e.g. login to Firebase with that token, or simply continue to make requests to the Facebook API!
We try to load a few fields from the current user which is in this case “me” and set the data from the result to our local userData variable
. You can test out all the Graph API fields and calls with the Facebook Graph API Explorer!
Now to the code, replace all inside your src/pages/home/home.ts with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook'; import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { userData: any; constructor(private facebook: Facebook) { } loginWithFB() { this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height(720).as(picture_large)', []).then(profile => { this.userData = {email: profile['email'], first_name: profile['first_name'], picture: profile['picture_large']['data']['url'], username: profile['name']} }); }); } } |
Once your user is logged in, you should now see all of the data inside the view like in the image below of my profile!
I hope this helps you to implement Facebook login in your Ionic app, it really comes down to just a few steps and is something all modern apps have for their users!
You can find a video version of this Quick Win below.
hey simon, can i make it with firebase together? I mean in firebase there is option to make Sign in with facebook so when I do this tutorial, if I use “this auth.state” it will know if i log inlogout if i use also with firebase?
Hey @azdir:disqus, do you having success on this integration? I need to do this too! Thanks!
How do I navigate to another page after logging in with facebook?
if you check https://ionicframework.com/docs/native/facebook you can found the logic to do whatever you want after login.
I got it working 🙂 Thanks
Hi. How were you able to get this to work?
Hi
Make sure you are using
@ViewChild(Nav) nav: Nav;
in your ts file, where you are placing the navigation code
Thanks very much for your help.
Will you share your code? Thank You.
Will you share your little code? Thank You.
Awesome post Simon, I was searching around for how to get the users profile pic and this really helped. Cheers.
Oh im also writing up a post about how to deal with the ‘account exists with different credentials’ issue with firebase if they have already signup with a username and password – will send it to you when done.
Hello RhysC i am having difficulty using firebase.auth() with this example i see youve done it care to shed some light. This is what is used previously. i am retrieve first and last name to save in my firebase database
facebookLogin(){
this.facebook.login([‘public_profile’,’email’]).then( (response: FacebookLoginResponse) => {
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCredential)
.then((newUser) => {
debugger
this.userProfile.child(newUser.uid).set({
email: newUser.email,
points:0,
firstName: newUser.displayName
})
console.log(“Firebase success: ” + JSON.stringify(newUser));
})
.catch((error) => {
console.log(“Firebase failure: ” + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}
i have getting ‘The provided app ID does not look like a valid app ID’ error.What is the way of removing this error?
when user login with facebook, I want to store user data to the mysql database , please help me with this
Have a method/function below the following (this.userData) that takes your user data object and send it to your rest api.
this.userData = {email: profile[’email’], first_name: profile[‘first_name’], picture: profile[‘picture_large’][‘data’][‘url’], username: profile[‘name’]}
Something like
userService.signupWithFacebook(this.userData).then(success => console.log(‘success’)).catch(errors => console.log(errors));
Hi bonny how do i use with facebook credential to log into firebase
const facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
console.log(“Firebase success: ” + JSON.stringify(success));
this.userProfile = success;
Thanx for this post simon.
hey anyone help me?
@supriya_babar:disqus I have written this code after that stored all data into nativestorage in ionic app.
But how to stored data into mysql database? (Want same database manged for APP & Website)
Please anyone give me solution or suggestion.
Hello, I have this error: “cordova_not_available”, What can be ?
Run your app on real device or emulator
or use ionic cordova run browser
How about implementing Google login
I doesnot tried it.
Thanx Sir…..
How to divert to new page after login?
use this method to facebook remote logout
http://www.townoftech.com/facebook-remote-logout/
i tried this not working for me .i am getting this
App Not Setup: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions. message please help
woderful tuto.
it only work for endroid emulator but not on real device. how to figure out?
login with facebook only work for my account ,When i try with other peoples id it does not work is gives https://uploads.disquscdn.com/images/4a2420ff693a0f403b97ece5574e11c3a980abc1e67df4bd888d1f4a1dee36ad.png Error shown in the image.Please help me. How to Remove Development Mode or add other mode.
Is it possible to store les image in database or somewhere else in the app for futher usage ?
https://uploads.disquscdn.com/images/079db2635e4497482a4510400d1afe1a6e412f041a2723b0cc9f7daa5d1d18ba.png
You do not have any hash keys in your training videos. How is it possible?
I get this error when I create a Hash Key and save it in the Developer console. What is the problem ?
In my app when i tried to login through facebook, the app name displays on facebook login page is another app name from my facebook developer profile. https://uploads.disquscdn.com/images/0381304bbc32956bd5d3d8a17d2962bedf2604c66fb2fa526d79746625b1f468.png
Hi, Im getting Object is not a function. Somebody know to solve it?