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

Download a file with Angular2+ and FileSaver.js

Why should your Angular code download a file? Of course your webserver can deliver files and you can just add a simple link to your website but what if the file is delivered by a webservice and the webservice requests authentication (i.e. OAuth) to protect the file from unauthorized access? In this case you might have the requirement to download the file in your code and then tell the browser to save it to the hard disk. How to do that?   First of all you need to add filesaver.js to your project.  npm install file-saver --save ..and add the typings npm install @types/file-saver --save-dev More information about filesaver you can find on the filesaver github pages . To download the file via http you need to implement a service. The following imports are required: import  {  Injectable  }  from   '@angular/core' ; import  {  Http ,  Response ,  RequestOptions ,  ResponseContentType  }  from   ...

Angular 2: Multiple instances in the same Application

Requirement:  Use multiple Root-Components in the same Application  This Root-Components use the same Implementations and Services Display the Root-Components on the same Single-Page Solution: App-Module preparation: import { BrowserModule, DOCUMENT } from '@angular/platform-browser'; import { NgModule, Inject, Component } from '@angular/core'; export class AppModule { private browser_document; ngDoBootstrap(appRef){ if(this.browser_document.getElementsByTagName('app-root1').length > 0){appRef.bootstrap(AppComponent1);} if(this.browser_document.getElementsByTagName('app-root2').length > 0){appRef.bootstrap(AppComponent2);} } constructor(@Inject(DOCUMENT) private document: any){ this.browser_document = document; } } Service preparation: Angular 2 has two options to provide a service. 1. Single instance For a multiple implementation of more Root-Components we need the second opt...