Friday, February 17, 2017

Firebase - Github Authentication

In this chapter we will show you how to authenticate users using Github API.

Step 1 - Enable Github Auth

Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar.
You need enable Github authentication and copy Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2.

Step 2 - Create Github App

Follow this link to crate Github app.
You need to copy Callback URL from Firebase into Authorization callback URL field.
Once your app is created you need to copy Client Key and Client Secret from Github app to Firebase.

Step 3 - Create Buttons

We will add two buttons in body tag.

index.html

<button onclick = "githubSignin()">Github Signin</button>
<button onclick = "githubSignout()">Github Signout</button>

Step 4 - Create Auth Functions

We will create functions for signin ans signout inside index.js file.

index.js

var provider = new firebase.auth.GithubAuthProvider();

function githubSignin() {
   firebase.auth().signInWithPopup(provider)
   
   .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
  
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
  
      console.log(error.code)
      console.log(error.message)
   });
}

function githubSignout(){
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed')
   });
}
Now we can click on buttons to trigger authentication. Console will show that the authentication is succesful.
Firebase Github Auth Log

No comments:

Post a Comment