Integrate Google Oauth in your Node.Js applications
Google Oauth is an authentication API by Google which makes logging in easy for users as well as for developers for storing the user data.
Ever wondered how different sites use Google authentication in order to make your signup/login process a whole lot easier. Well, Google Oauth is something that they use in order to achieve this.
We are going to go step by step about how to apply this in your Node.Js applications using Passport.Js and Express.Js
First of all, making an app.js file in your root directly and starting a server using Express.Js and mongoose to connect to your MongoDB database. In order to do this, you’ll need to install all the npm dependencies. To initialize ‘npm’ in your project use in your terminal:
Workflow
Project Initialization
npm init
and set all the options as per your wish, I usually keep them in their default state.
You should be able to see something like this in your terminal.
After you are done with this NodeJs would create a package.json file for you, where all your dependencies and their versions should be visible.
After that use
npm i express mongoose body-parser dotenv
in order to install all the required dependencies to start a server and connect with MongoDB.
App.js initialization
Initialise your express server and MongoDB using the code below
const express = require(“express”);
const mongoose = require(“mongoose”);
const bodyParser = require(“body-parser”);
require(“dotenv”).config();const app = express();const dbURI = process.env.dbURI; //Add your database URL string heremongoose
.connect(dbURI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
}).then(() => console.log(“Database Connected”))
.catch((err) => console.log(err));mongoose.Promise = global.Promise;//route not foundapp.use((req, res, next) => {
const error = new Error(“Route not found”);
error.status = 404;
next(error);
});app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});const PORT = process.env.PORT || 3000;app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
Your terminal should log when you use :
node app.js
Voila! You’ve successfully initialised the server and connected your database
We need to make a user model in the models folder inside your root directory who is going to login to our app using Google Oauth having code :
User model
const mongoose = require(“mongoose”);
const userSchema= mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
googleId: {type: String,},
name: { type: String },
email: {
type: String,
match: /[a-z0–9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0–9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0–9](?:[a-z0–9-]*[a-z0–9])?\.)+[a-z0–9](?:[a-z0–9-]*[a-z0–9])?/,
}
});module.exports = mongoose.model(“User”, userSchema);
This is the user schema that we are going to use in order to store the user in our database
Create a routers model and add user.js and auth.js files to it, your directory should now look like :
After you’re done creating the model, it is time to explore the Google Oauth API
Go to
Google API setup
Creating project and enabling API
Click on select a project and create a new project :
Enter your project name and organisation name if any :
Now enable API and Services
Now search for Google+ and select the Google+ API and Enable it
You should be brought to a page like this and now click on create credentials
select Google+ API on the form and save the access key somewhere with you .
Configuring and generating Credentials
You would then be redirected to a page like this and click on configure the consent screen
Select External if you want all the Google users to be able to signup and fill the next page as shown by changing your project name
After you save it successfully, go to credentials page and click on create credentials and select OAuth client ID
Now this Form should open select your application type and enter your application name, now enter the URLs as I’ve done and you are good to go
A dialog box like this should occur with your credentials, make sure you save the credentials somewhere
You are now all set on the Google developer console and now going back to VScode to setup our Passport.Js
Create a config folder in the root directory and add the passport-setup.js file to it.
npm i passport-google-oauth20
Google-passport-setup
Now inside the passport-setup.js file add this snippet of code
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/user');
const mongoose = require('mongoose');passport.serializeUser((user, done) => {
done(null, user.id);
});passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user);
});
});passport.use(new GoogleStrategy({
// options for google strategy
clientID: /* your clientID*/"" ,
clientSecret:/*your clienSecret*/"",
callbackURL: '/auth/google/redirect'
}, (accessToken, refreshToken, profile, done) => {
// check if user already exists in our own db
User.findOne({googleId: profile.id}).then((currentUser) => {
if(currentUser){
// already have this user
console.log('user is: ', currentUser);
done(null, currentUser);
} else {
// if not, create user in our db
new User({
_id: new mongoose.Types.ObjectId(),
googleId: profile.id,
name: profile.displayName,
email:profile._json.email
}).save().then((newUser) => {
console.log('created new user: ', newUser);
done(null, newUser);
});
}
});
})
);
Now explaining the snippet above, we first import all the necessary packages and file that we are going to use in the code. Enter your clientID and clientSecret that you received from Google developers console.
What is callbackURL — It is the URL on which Google will redirect your users to once they have successfully signedup/logged in. The access token is a token generated by Google which is automatically entered into the callback function in order to authenticate the user that just signed in, refreshTokens are used for offline apps, the profile is something that contains the user’s entire data which is returned from Google, I only took the data which my user model requires which is googleId, name and email but if you
console.log(profile)
you will get the entire user data that Google allows you to have.
The functions serializeUser and deserializeUser are used in order to generate cookies and actually get the user data when the user signs in so that he/she can be authenticated and the data could be further processed
Routes and final setup
Auth Routes
Now in /routers/auth.js add this code :
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");const router = express.Router();router.get("/google",passport.authenticate("google", {
scope: ["profile", "email"],
})
);///Callback route for google to redirectrouter.get("/google/redirect", passport.authenticate('google'),(req, res, next) => {
user = req.user
res.send(user)
});module.exports = router;
The scope used in router.get(“/Google”…..) is to define which data fields we actually require from Google according to the profile in the callback function as we recall
It will automatically redirect you to /auth/Google/redirect as we added that to the callbackURL in the GoogleStrategy function in passport-setup.js
App.js Final additions
Now in app.js add this snippet of code before calling the mongoose.connect() function:
const passportSetup = require(".config/passport-setup");
const passport = require("passport");const authRoutes = require(".routers/auth");// initialize passport
app.use(passport.initialize());
app.use(passport.session());app.use("/auth", authRoutes);
app.use(“/auth”,…..) because the URL to redirect to Google signup/login using http://localhost:3000/auth/Google
Testing and checks
you now run the app using node app.js you should still see the same console.log() which you saw in the beginning. Now open your browser and go to http://localhost:3000/auth/Google, It should redirect you to the Google sign-in page
Once you select any account it should redirect you to router.get(‘/Google/redirect’,…..) in which we sent the data of the user as a response, you can redirect directly from there using res.redirect too.
but what we have kept should display an output page like
which has already been saved to the database you created.
Congrats you’ve successfully integrated the Google Oauth API in your nodejs application.
Github repository link : https://github.com/jugaldb/Google-Oauth-Nodejs