Firebase (sign in with Google) Authentication in Node.js using Firebase UI and Cookie Sessions
Last Updated :
26 Aug, 2020
Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app.
Prerequisites: Basic knowledge of node, JavaScript and firebase.
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.
javascript
const express = require("express");
const admin = require("firebase-admin");
const cookieParser = require("cookie-parser");
const https = require('https');
const fs = require('fs');
const app = express();
app.use(cookieParser());
var key="--BEGIN PRIVATE KEY--\nMIIEvgIBADANBgk"
+ "qhkiG9w0BAQE--your key here--+1d4\n--END"
+ " PRIVATE KEY-\n";
admin.initializeApp({
credential: admin.credential.cert({
"private_key": key.replace(/\\n/g, '\n'),
"client_email": "YOUR CLIENT EMAIL HERE",
"project_id": "YOUR PROJECT ID "
})
});
app.get('/', (req, res) => {
res.sendFile(__dirname +'/login.html');
});
app.get('/logout', (req, res) => {
res.clearCookie('__session');
res.redirect('/');
});
app.get('/success', checkCookie, (req, res) => {
res.sendFile(__dirname + '/success.html');
console.log("UID of Signed in User is"
+ req.decodedClaims.uid);
// You will reach here only if session
// is working Fine
});
app.get('savecookie', (req, res) => {
const Idtoken=req.query.token;
setCookie(Idtoken, res);
});
// Saving cookies and verify cookies
// Reference :
//https://firebase.google.com/docs/auth/admin/manage-cookies
function savecookie(idtoken, res) {
const expiresIn = 60 * 60 * 24 * 5 * 1000;
admin.auth().createSessionCookie(idtoken, {expiresIn})
.then((sessionCookie) => {
const options = {maxAge: expiresIn,
httpOnly: true, secure: true};
admin.auth().verifyIdToken(idtoken)
.then(function(decodedClaims) {
res.redirect('/success');
});
}, error => {
res.status(401).send("UnAuthorised Request");
});
}
function checkCookie(req, res, next) {
const sessionCookie = req.cookies.__session || '';
admin.auth().verifySessionCookie(
sessionCookie, true).then((decodedClaims) => {
req.decodedClaims = decodedClaims;
next();
})
.catch(error => {
// Session cookie is unavailable or invalid.
// Force user to login.
res.redirect('/');
});
}
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-
javascript
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app)
.listen(3000, function () {
console.log('listening on port 3000!'
+ ' Go to https://localhost:3000/')
});
Load this script before body tag in login page
HTML
<!-- Firebase Package-->
<script src=
"https://www.gstatic.com/firebasejs/5.8.5/firebase.js">
</script>
<!-- Loads the login UI elements-->
<script src=
"https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js">
</script>
<link type="text/css" rel="stylesheet" href=
"https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" />
Load this script in login page after body tag (fill the config data that you got from firebase console).
javascript
var config = {
apiKey: "YOUR_KEY",
authDomain: "YOUR_DOMAIN",
databaseURL: "YOURURL",
projectId: "--",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
firebase.initializeApp(config);
firebase.auth().setPersistence(
firebase.auth.Auth.Persistence.NONE);
// FirebaseUI config.
var uiConfig = {
signInOptions: [
// Google sign in option
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
],
// Terms of service url/callback.
tosUrl: '<your-tos-url>',
// Privacy policy url/callback.
privacyPolicyUrl: function () {
window.location.assign(
'<your-privacy-policy-url>');
},
callbacks: {
signInSuccess: function (user,
credential, redirectUrl) {
// User successfully signed in.
user.getIdToken().then(function (idToken) {
window.location.href =
'/savecookie?idToken=' + idToken;
}).catch(error => {
console.log(error);
});
}
}
};
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
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
Reference: https://firebase.google.com/docs/auth/admin/manage-cookies
Similar Reads
Google SignIn using Firebase Authentication in ReactJS
Firebase simplifies mobile and web app development by offering pre-built features like user authentication (email/password, Google Sign-In, etc.) without the need to build complex backends. This saves time and resources for developers.In this article, we will discuss about the Google Sign-In feature
5 min read
How to authenticate with google using firebase in React ?
The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so.Creating React Application And Installing Module:Step 1: Create a React myapp using the following command:npx create-react-app myappStep 2: After creating your project fo
2 min read
Implementing User Authentication with Next JS and Firebase
In this article, we are going to learn how we can use Firebase with Next JS to implement user authentication. So, that user can log in using their credentials or Google account. For this project, sound knowledge of Next JS and FIrebase is required. If you are new then, don't worry every step in this
6 min read
Integrating Real-time Database and Authentication using Next JS and Firebase
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn how to integrate Firebase's real-time database
5 min read
Google Authentication using Passport in Node.js
The following approach covers how to authenticate with google using passport in nodeJs. Authentication is basically the verification of users before granting them access to the website or services. Authentication which is done using a Google account is called Google Authentication. We can do Google
2 min read
How to add authentication in file uploads using Node.js ?
There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer. We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb. There are many module
3 min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online servic
8 min read
Basic Authentication in Node.js using HTTP Header
Basic Authentication is a simple authentication method where the client sends a username and password encoded in base64 format in the HTTP request header.The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js
3 min read
How to delete file from the firebase using file url in node.js ?
To delete a file from the Firebase storage we need a reference to store the file in storage. As we only have the file URL we need to create a reference object of the file in Firebase storage and then delete that file. Deleting a file using the file URL can be done in two steps - Get the reference to
2 min read
How to Delete User Account from firebase authentication in web ?
We are working on the firebase series, Firebase gives various functions to use in our application. like database, authentication, hosting, etc., In this article, we will see how to delete a user account from the firebase authentication.Firebase has a delete function that deletes the user account fro
3 min read