Skip to main content

Social Login with Angular 4 and FireBase

There is a way to let users use there social logins to get access to Firebase. But how do you implement this login to your Angular 4 project. In this article I will tell you how to set up your Firebase database and how do you implement social login to your angular project.

Set up Firebase


First we have to get our database ready. In your Firebase Console you will find Authentication in the left navigation bar.


At the tab Sign-In Method you can enable different sign in methods. In our example we will enable Google and Facebook, as it's the most commend social login methods these days.




The Google Login will be configured automatically.

When you enable Facebook Login you need an App ID and an App Secret. You will get these when you register yourself as a developer at Facebook. You can read how you can do that at the Facebook Site. I will not explain you that in detail because it's very easy.

If we done, it's time to set up our Angular4 code.

Install Angularfire2

Angularfire2 is an Observable based real-time binding, authentication method.

If you want to read more about Angularfire2, you can read the documentation on GitHub

First we have to install angularfire2 firebase to our Angular4 project.
npm install angularfire2 firebase --save

After this you have to install typing for firebase, too
npm install @types/firebase

and adding this typing to your tsconfig.spec.json
"typeRoots": [
      "../node_modules/@types"
    ],
"types": [
      "jasmine",
      "firebase",
      "node"
    ]

In the end your config will look like this
{
  "extends""../tsconfig.json",
  "compilerOptions": {
    "outDir""../out-tsc/spec",
    "module""commonjs",
    "target""es5",
    "typeRoots": [
      "../node_modules/@types"
    ],
    "baseUrl""",
    "types": [
      "jasmine",
      "firebase",
      "node"
    ]
  },
  "files": [
    "test.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}


Configure Angular4 for Angular Fire

Than we import the AngularFire Modules we need to our app.moduls.ts
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';


Now we have to tell the Angular Project our Firebase configuration. The best way to do this is to export a constant. In this case I named it firebaseConfig.
export const firebaseConfig = {
  apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};


You will find the configuration in your Firebase Console at Project Settings.





Then clicking on Web-App and you can copy the configuration to your app.moduls.ts.



After this we have to do our imports and that's it for the app.moduls.ts
 imports: [
    BrowserModule,
    AngularFireAuthModule,
    FormsModule,
    HttpModule,
    AngularFireModule.initializeApp(firebaseConfig),
  


Set up app.components.ts

As you know Angular Fire is Observable driven. So we have to import Observable from rxjs. We also need AngularFireAuthModule and AngularFireAuth. At last we need the import the regular firebase JS Library. That's it



import { Observable } from 'rxjs/Observable';
import { AngularFireAuthModuleAngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';


We declare a variable called user as an Observable from type firebase.user
  userObservable<firebase.User>


Now we have to initialize the Angular Fire Authentication.
constructor(private afAuthAngularFireAuth){
  this.user = this.afAuth.authState
}


Set up Login Methods

Now we can set up the different login Methods. In these example I am using Facebook and Google.

Google:
 loginGoogle() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
      .catch(function (error){
      alert('${error.message} Please try again')
    })
  }

Facebook:
loginFacebook() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
    .catch(function (error){
      alert('${error.message} Please try again')
    })
  }

We need also a log out method.

Logout


 logout() {
    this.afAuth.auth.signOut();
  }


Template:


If we done all the code, we are ready to create our template.
The button styling, I copied from codepen.io. Thank you for that.
It's looking like this


Don't forget to add the click event on the buttons.


<h1>
  Login
</h1>
<div>
  <button class="loginBtn loginBtn--facebook" (click)="loginFacebook()" *ngIf="!(user | async)?.uid">
  Login with Facebook
</button>
  <br>
  <button class="loginBtn loginBtn--google" (click)="loginGoogle()" *ngIf="!(user | async)?.uid">
  Login with Google
</button>
  <br>
  <button (click)="logout()" *ngIf="(user | async)?.uid">Logout</button>
  <br><br>
</div>
<div *ngIf="(user | async)?.uid">
  <img src="{{(user | async)?.photoURL}}" style="width:30px;height:30px;">
  <br> Email: {{(user | async)?.email}}
  <br> Name: {{(user | async)?.displayName}}
</div>

I also add the Email, Photo and the Name from the current user. It's hidden when nobody logged in.
*ngIf="(user | async)?.uid"

So let's try our buttons.

First Facebook



And second Google

As you see it's working fine. We are logged in.





Now let's look in our Firebase Database. If we see our Google Account there



There is my account, super!




That's it! Not complicated at all, isn't it

Comments

Popular posts from this blog

Create a simple Messageboard with Firebase and Angular4

You want that your users can leave messages in your Angular Application. In this Article I explain how you can implement this with Angular 4 and Firebase. First we have to import the Moduls for Firebase in our app.module.ts and our component. app.module.ts import  {  AngularFireModule  }  from   'angularfire2' ; import  {  AngularFireDatabaseModule ,  AngularFireDatabase ,  FirebaseListObservable  }  from   'angularfire2/database' ; @ NgModule ({    declarations:  [      AppComponent   ],    imports:  [      BrowserModule ,      FormsModule ,      HttpModule ,      AngularFireModule . initializeApp ( firebaseConfig ),      AngularFireDatabaseModule , We also have to configure the AngularFireModule. export   const   fireba...

Utilize 3rd party Javascript libraries in your Angular 2+ application with CLI

Not everything is available as a native Typescript library. Due to that sometimes you might need to use 3rd party libraries. After creating a new project with Angular CLI you will experience that VS Code does not know any libraries you have imported in the header tag and the compiler complains when you try to use this libraries. The reason is: You are missing the typings. The typings describe the functionality of the libary and make that available in your project through intellisense and for the compiler. But before you start creating your own typings do the following checks: 1. Does the vendor of the library provide the typings? If yes, install through npm 2. Are the typings available on definitely typed ? If yes, then take it from there. If this is not the case then you can do your own typings. If you want to do that properly, then you should write the complete set of typings for the library and upload to definitely typed to provide it for the community. OK, this might b...