Google Auth with Node.js Restful API
In modern companies frequently use Google sign in system for their web sites or web applications. In this article we are going to look how to implement Google login system to Nodejs based backend.
There are 5 main steps in the process.
Prerequisites
- JavaScript Knowledge
- Google Account
- Postman
Step 1 of 5
First of all we need to create a new Google project. For that click here.
- Go to projects -> New project and create a new project
2. After creating new project select the create credentials from credential tab. Then choose OAuth client ID.
3. If you are successfully created OAuth client, you get an client id and client secret. Copy those values to the nodepad or something else.
Step 2 of 5
In the actual process frontend get some access token from google servers. But in here we are not going to implement a frontend. Therefore we assume that we got access token from google servers and it has been send in request body. So we need to call the Rest API endpoint with access token as a parameter. We need a HTTP request handler and here, we are going to use Postman for that process. you can download postman here.
You can also refer documentation here.
Enough talking..Now we just need a access token. how can we get this?
Solution is Google auth playground service offer by google. You can go to the service here. These are steps to follow,
- You need to choose Google AuthAPI version 2. According to your requirement(Lets say you are going to store username and user email, then you need to choose both) choose the fields and click Authorize APIs.
- You need to choose a google account. Access token will generate to authorize this google account.
- Next, click Exchange authorization code for tokens button. It will generate a access token.(Remember this access token will only valid within number of minutes). Copy that access token also.
Step 3 of 5
Install Packages
We are going to use a passport-google-plus-token package provided by passport.js. This is a passport strategy for authenticating with google access tokens using the OAuth 2.0 API.
use the npm to install
npm install passport-google-plus-token
or yarn
yarn add passport-google-plus-token
also we need to install Json web token package. Then we can communicate with clients with generated web token. you can refer this for learn more.
npm install jsonwebtoken
or yarn
yarn add jsonwebtoken
Create User Model
Here we are going to use mongodb as the database in our system.
import {Schema}, mongoose from “mongoose”;
import jwt from "jsonwebtoken";const UserSchema = ({
username:{type: String},
email:{type: String}
});UserSchema.methods = {createToken() {return jwt.sign({_id: this._id,},constants.JWT_SECRET);},toAuthJSON() {return {_id: this.id,username: this.username,token: this.createToken(),};},
}module.exports = mongoose.Schema("User", UserSchema);
Step 4 of 5
Create a middleware
We need to Create a middleware for google strategy. create a auth.js file and add this code there.
import passport from “passport”;
import GooglePlusTokenStrategy from "passport-google-plus-token";import User from "../modules/users/user.model";// Google Plus Strategyconst googleConfig = {clientID: "xxxxxxx", // Your client idclientSecret: "xxxxxxxx", // Your client secret};const googleStrategy = new GooglePlusTokenStrategy(googleConfig,async (accessToken, refreshToken, profile, done) => {try {const user = await User.findOne({ "google.id": profile.id });if (!user) {const newUser = await User.create({email: profile.emails[0].value,username: profile.displayName,});return done(null, newUser);}return done(null, user);} catch (e) {return done(e, false);}});passport.use(googleStrategy);export const authGoogle = passport.authenticate("google-plus-token", {session: false});
Remember profile field would generate the profile details. It contains much more details including media url’s. But here we are using only profile email and username.
Create a route
Add this code to your routes file that contains API endpoints.
import { Router } from “express”;
import { authGoogle } from "./auth";import * as userController from "./user.controller";// POST -> user google+ signuproutes.post("/api/v1/users/google", authGoogle, userController.googleSignup);export default routes;
Create User Controller
Add this code to the user controller file.
import User from “./user.model”;
import HTTPStatus from “http-status”;export const googleSignup = async (req, res, next) => {res.status(HTTPStatus.CREATED).json(req.user.toAuthJSON());return next();};
Note: You will need http-status package. This is not mandatory package. you can replace normal HTTP response codes also.
Step 5 of 5
Now open postman and create a virtual POST route for calling our API endpoint. Then send above copied access token got from google playground in request body.
Now you see response include the Json web token. Now this token can be used as access token for some routes.
So If you have any problem put it in the comment section below.