Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app.
Setup: First we need to create a Firebase Project, head over to firebase Console and create a new project.
I am going to name it SignInWithGoogle
Click on the web to create a web app.
Go to Firebase Settings>Service Account >Generate a new Key. This Key should be remain private, It is advised to keep this in environment variables.
Now go to Authentication tab and turn on Sign in with Google.
Now Create a new project having success.html (with a simple anchor tag, directing to “/ ” root ) and login.html [leave a blank division with id “firebaseui-auth-container”, the place where Firebase UI will be Initialized]
Change console directory to root of your project type by using the following commands in the console
$npm init $npm install express firebase-admin cookie-parser https fs
Note: The last two packages are only needed if you wanna save cookies in local-host, however, if you will be running a backend on https then there is no need.
Here is app.js file, If you look it closely, you will find that there is no port listening to our request. This is where we need those two node modules.
Most browsers does’t allow you to save cookies in local host, that’s why we will setup HTTPS connection for our localhost.
Make sure you are in root directory of project.
Open bash and type
$openssl req -nodes -new -x509 -keyout server.key -out server.cert
Two files (server.key and server.cert) will be generated.
Add the following code to app.js file-
Load this script before body tag in login page
Load this script in login page after body tag (fill the config data that you got from firebase console).
Now hit save and run the command $node app.js
Now go to https://localhost:3000/ and sign in, then close the tab or browser and type https://localhost:3000/success, you will see that you are not redirected to the sign-in page again, instead, you are taken to the success page.
Note: Here it didn’t ask me to select which account to login with the app because I was signed in with only one account, in-case you have signed in with multiple accounts, it will ask you to choose an account to proceed with.
Download My Completed project in case of any error you face or write in the comment
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.