Adding Firebase Authentication to Your Web Application
Tags: firebase, webdev
Published: 2023-01-21 14:44:45

<p>In the <a href="https://medium.com/@codersalman/firebase-for-web-a-step-by-step-tutorial-bf4da59c0a02">previous</a> article of our <strong>Firebase for Web</strong> series, we looked at how to configure Firebase with a web app and add services like Analytics and Realtime Database. In this article, we will continue the series by covering another important topic from<strong> Firebase: Authentication with web apps</strong>. By the end of this article series, you will be a Firebaser (Firebase expert) and able to add robust authentication and authorization to your web applications.</p><p>Check out the <a href="https://medium.com/@codersalman/firebase-for-web-a-step-by-step-tutorial-bf4da59c0a02">previous</a> article :</p><p><a href="https://medium.com/@codersalman/firebase-for-web-a-step-by-step-tutorial-bf4da59c0a02">Firebase for Web: A Step-by-Step Tutorial</a></p><p>As we know user authentication and authorization is a crucial aspects of any web application.</p><p>Firebase Authentication is a service provided by Firebase that makes it easy for developers to add this functionality to their web applications.</p><p>With support for multiple authentication methods such as email and password, phone number, and social media providers like Google, Facebook, and Twitter,</p><p>Firebase Authentication is a versatile and powerful tool for web developers. In this article, we will be diving into how to use Firebase Authentication in your web application, including how to set it up and how to use its various features.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8sGY55yxicA%3Ffeature%3Doembed&display_name=YouTube&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8sGY55yxicA&image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8sGY55yxicA%2Fhqdefault.jpg&key=a19fcc184b9711e1b4764040d3dc5c07&type=text%2Fhtml&schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd137e21235dd7b88c1aff7c841529ae/href">https://medium.com/media/fd137e21235dd7b88c1aff7c841529ae/href</a></iframe><p>Here’s a Step by Step Guide to adding email & password authentication in the web app</p><p>Enable the Authentication Service in Firebase Console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nwd8vKJIavbZr2NjY5rI5A.png" /></figure><ol><li>Initializing Firebase in a Web Application (check out the <a href="https://medium.com/@codersalman/firebase-for-web-a-step-by-step-tutorial-bf4da59c0a02">previous article</a> or check <a href="https://firebase.google.com/docs/web/setup">Firebase docs</a>)</li></ol><pre><script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js"></script></pre><pre>var firebaseConfig = {<br>    apiKey: "your-api-key",<br>    authDomain: "your-project-id.firebaseapp.com",<br>    databaseURL: "https://your-project-id.firebaseio.com",<br>    projectId: "your-project-id",<br>    storageBucket: "your-project-id.appspot.com",<br>    messagingSenderId: "your-sender-id",<br>    appId: "your-app-id"<br>  };<br>  firebase.initializeApp(firebaseConfig);</pre><p>2. Using the Firebase Authentication SDK in Web App</p><p>Add this to your Index.html file and create a form in to get the user email and password</p><pre><script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-app.js"></script></pre><pre><!-- Add this to the body of your HTML file --><br><form><br>  <label>Email:</label><br>  <input type="email" id="email"><br>  <br><br>  <label>Password:</label><br>  <input type="password" id="password"><br>  <br><br>  <button type="button" onclick="signUp()">Sign Up</button><br>  <button type="button" onclick="signIn()">Sign In</button><br>  <button type="button" onclick="signOut()">Sign Out</button><br></form></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUNgsl8sMShaW2bpQY96gw.png" /></figure><p>So we have created a webpage of our web app with a form including 2 input fields and 3 buttons to perform auth functions with the email password method with Javascript’s OnClick method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVXNN_EuedQhGiswdEzEAQ.png" /><figcaption>Enable Email/Password Method in console</figcaption></figure><p>3. Create an Auth.js and Initialize it in Index.html</p><pre>  <br>   // To get the User Entered Values from the WebPage<br>  var emailInput = document.getElementById("email");<br>  var passwordInput = document.getElementById("password");</pre><p>Now to Enable the Signup function will use the firebase’s function</p><pre>createUserWithEmailAndPassword("your@email.com", "userpassword")</pre><p>Now here’s the signup function to create a new user account</p><p>will use the firebase app-initialized variable with auth() function to call the create, sign in, and sign out the user from the web app</p><p>Add the following code in Auth.js for each function to call onClick</p><h3>SignUp :</h3><p>Create a new user with an email and password</p><pre> function signUp() {<br>    var email = emailInput.value;<br>    var password = passwordInput.value;<br>    firebase.auth().createUserWithEmailAndPassword(email, password)<br>      .catch(function(error) {<br>        var errorCode = error.code;<br>        var errorMessage = error.message;<br>       console.log('Error: '+ errorMessage)<br><br>      });<br>  }</pre><h3>SignIn :</h3><p>Sign in an existing user with email and password</p><pre>  function signIn() {<br>    var email = emailInput.value;<br>    var password = passwordInput.value;<br>    firebase.auth().signInWithEmailAndPassword(email, password)<br>      .catch(function(error) {<br>       console.log('Error: '+ errorMessage)<br>      });<br>  }</pre><h3>Sign Out :</h3><p>Sign out the current user</p><pre> function signOut() {<br>    firebase.auth().signOut().then(function() {<br>      // Sign-out successful.<br>    }).catch(function(error) {<br>      var errorCode = error.code;<br>      var errorMessage = error.message;<br>// Handle Errors here.<br>console.log('Error: '+ errorMessage)<br>    });<br>  }</pre><p>Now we are done with all necessary functions so, now we can create, sign, and sign out of our web application</p><p>In order to enable the user to stay logged in even if the page is refreshed, you can use the onAuthStateChanged method to detect changes in the user's authentication state and update the UI accordingly.</p><p>Here's an example of how to use this method:</p><pre>firebase.auth().onAuthStateChanged(function(user) {<br>  if (user) {<br>    // User is signed in.<br>console.log('User Logged in with email ' +  user.email)<br>    document.getElementById("email").innerHTML = user.email;<br>    document.getElementById("sign-out").style.display = "block";<br>    document.getElementById("sign-in").style.display = "none";<br>    document.getElementById("sign-up").style.display = "none";<br>  } else {<br>    // User is signed out.<br>console.log('User Signed Out')<br>    document.getElementById("email").innerHTML = "";<br>    document.getElementById("sign-out").style.display = "none";<br>    document.getElementById("sign-in").style.display = "block";<br>    document.getElementById("sign-up").style.display = "block";<br>  }<br>});</pre><p>after handeling the userAuth state</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrCls6Zi6vF-AMWac6lXhQ.png" /></figure><p>Check out the Github Repo Given below</p><p><a href="https://github.com/codersalman/firebase_auth">GitHub - codersalman/firebase_auth</a></p><p>In conclusion : Firebase Authentication provides a flexible and secure solution for managing user accounts in your web app.</p><p>I hope this article has provided you with a solid foundation for working with Firebase Authentication in your web applications. Remember to test your implementation thoroughly, handle errors properly and don’t hesitate to refer to the Firebase Authentication documentation for more information and best practices.</p><p>Thank you for reading this article and I hope it has been helpful in your journey of web development with Firebase. I look forward to providing more insights and tips on Firebase in the future. If you have any questions or feedback, please feel free to reach out on coder88salman@gmail.com.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe9174bef24" width="1" height="1" alt=""></br><p style="color:#757CF9;">This article is published w/ <a target="_blank" href="https://scattr.io?ref=dev">Scattr  ↗️</a></p>