In this part, we I'll show you how to authenticate users using the GitHub.
To handle the sign-in flow with the Firebase JavaScript SDK, follow these steps:
- Add Firebase to your JavaScript project.
- In the Firebase console, open the Auth section.
- On the Sign in method tab, enable the GitHub provider.
- Add the Client ID and Client Secret from that provider's developer console to the provider configuration:
- Register your app as a developer application on GitHub and get your app's OAuth 2.0 Client ID and Client Secret.
- Make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app's settings page on your GitHub app's config.
- Click Save.
- Create an instance of the GitHub provider object:
var provider = new firebase.auth.GithubAuthProvider();
- Authenticate with Firebase using the GitHub provider object. You can prompt your users to sign in with their GitHub accounts either by opening a pop-up window or by redirecting to the sign-in page. The redirect method is preferred on mobile devices.
- To sign in with a pop-up window, call signInWithPopup
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) }); }
- To sign in by redirecting to the sign-in page, call signInWithRedirect
var provider = new firebase.auth.GithubAuthProvider(); function githubSignin() { firebase.auth() .getRedirectResult(provider) .then((result) => { if (result.credential) { var credential = result.credential; // This gives you a GitHub Access Token. You can use it to access the GitHub API. var token = credential.accessToken; } // The signed-in user info. var user = result.user; }).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... }); }
- To sign in with a pop-up window, call signInWithPopup
- Set an authentication state observer and get user data
firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. var displayName = user.displayName; var email = user.email; var emailVerified = user.emailVerified; var photoURL = user.photoURL; var isAnonymous = user.isAnonymous; var uid = user.uid; var providerData = user.providerData; // ... } else { // User is signed out. // ... } });
- To signOut user
function githubSignout(){ firebase.auth().signOut() .then(function() { console.log('Signout successful!') }, function(error) { console.log('Signout failed') }); }