DJANGO - OAuth with JWT | Brain Mentors Skip to content

OAuth with JWT

OAuth is Open Authentication used for User Authentication from 3rd Party Services ( Facebook , Gmail, Git , Twitter )
There is No Need of User Registration , to fill for our website. User Need to remember different passwords for different website accounts.
For Developer no need to maintain a code for Authentication , call 3rd Party Services for this

Now, Let’s see How OAuth Work

Now do Setup of Express App

Create a Project Folder

npm init -y
npm i express —save

Create app.js

const express = require(‘express’);
const app = express();
app.use(express.static(‘public’));
const server = app.listen(process.env.PORT || 1234,
()=>{
console.log(‘Server Start at Port
‘,server.address().port);
})

Run your server

nodemon app.js

Create a Folder called routes and inside the routes create userroutes.js

Add the Route code

const express = require(‘express’);
const router = express.Router();
router.get(‘/auth’,(request,response)=>{
});

router.get(‘/auth/cb’,(request,response)=>{
});

module.exports = router;

Now, Create a public folder and index.html file as shown

index.html-


<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=devicewidth, initial-scale=1.0″>
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<title>OAuth Demo – Brain Mentors Pvt Ltd</title>
<link rel=”stylesheet” href=”https:// stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/ bootstrap.min.css” integrity=”sha384- Vkoo8x4CGsO3+Hhxv8T/ Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifj h” crossorigin=”anonymous”>
</head>
<body>
<div class=”container”>
<a href=”/auth” class=”btn btn-primary”>Login with Google</a>
</div>
</body>
</html>

Using PassPort JS for OAuth

Passport is authentication middleware for Node. js.
It has lot of strategies support for authentication with FB , Gmail , Twitter.
It supports 500+ Strategies
reference : http://www.passportjs.org/

Install passort

Create a folder utils and create a file passport-config.js inside it

passport-config.js

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-googleoauth20’);
var google = new GoogleStrategy({
// key ,value for google Strategy go to google developer console :
console.developers.google.com
},()=>{
// passport callback function
});
passport.use(google); // it is like app.use console.developers.google.com

Create a new Project inside it

Select Your Created project

Select a project

Now Enable the API

Search for the Google+API

Enable the Google + API

Click on create credential to your project

Add credentials to your Project

Now, Your OAuth Client Id has been created SuccessFully

Now Maintain a Client Secret and Client Id in config file inside the utils folder

const config =
{
clientID:’YOUR CLIENT ID’,
clientSecret:’YOUR CLIENT SECRET’,
callbackURL:’/auth/cb’
}
module.exports = config;

Use Config file in passport

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-googleoauth20’);
const config = require(‘./config’);
var google = new GoogleStrategy({
clientID:config.clientID,
clientSecret:config.clientSecret,
callbackURL:config.callbackURL

// key ,value for google Strategy
},()=>{});
passport.use(google);// it is like app.use
module.exports = passport;

Configure the Passport setting in app.js so it will load early

const express = require(‘express’);
const app = express();
const passportConfig = require(‘./utils/passportconfig’);
app.use(express.static(‘public’));
app.use(‘/’,require(‘./routes/useroutes’));
const server = app.listen(process.env.PORT || 1234,
()=>{
console.log(‘Server Start at Port
‘,server.address().port);
});

Add the Middleware in the route for Login with Google

const express = require(‘express’);
const router = express.Router();
const passport = require(‘passport’);

router.get(‘/auth’,passport.authenticate(‘google’, {scope:[‘profile’,’email’]}));
router.get(‘/auth/cb’,(request,response)=>{
response.send(‘Done….’);

});
module.exports = router;

Now test this thing
Localhost:1234

Now Adding a Middleware for the call back url to get the callback result

const express = require(‘express’);
const router = express.Router();
const passport = require(‘passport’);

router.get(‘/auth’,passport.authenticate(‘google’,{scope: [‘profile’,’email’]}));

router.get(‘/auth/
cb’,passport.authenticate(‘google’),
(request,response)=>{
response.send(‘Done….’);
});

module.exports = router;

This will call the Callback function mentioned in passport config.js

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-googleoauth20’);
const config = require(‘./config’);
var google = new GoogleStrategy({
clientID:config.clientID,
clientSecret:config.clientSecret,
callbackURL:config.callbackURL // key ,value for google Strategy
},()=>{
Console.log(“I Will call “);
}
);
passport.use(google);// it is like app.use module.exports = passport;

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-googleoauth20’);
const config = require(‘./config’);
var google = new GoogleStrategy({
clientID:config.clientID,
clientSecret:config.clientSecret,
callbackURL:config.callbackURL// key ,value for google Strategy
},(accessToken, refeshToken, profile, done)=>{
// profile – gives profile of the users
//done is call back the first argument of done is err if occur and next is the data
// this call back trigger the (req, res) callback of the
route accessToken is given by google and to refresh the accessToken time to time google give refresh token we are not using both of them,
//Now u can do the find in DB , if not exist then insert in DB

console.log(“I Will Call “,profile);
});
passport.use(google);// it is like app.use module.exports = passport;

  • When the user logs in, the backend creates a signed token and returns it in response
  • The client saves the token locally (typically in localStorage) and sends it back in every subsequent request that needs authentication
  • All requests needing authentication pass through a middleware that checks the provided token and allows the request only if the token is verified

Now, Lets talk about JWT

JWT is a Token Based Mechanism instead of session based , so we can use this for any front end web or mobile app, where session work with cookies. JWT generate token and transfer token between client and server to maintain the conversational state as http working as a stateless protocol. Now we will Integrate with JWT

JWT (JSON Web token)



OAuth with JWT – Blog

npm install jsonwebtoken —save

OAuth with JWT – BlogCreate token.js inside the utils folder

const jwt = require(‘jsonwebtoken’);
module.exports = {
secret : ‘iamthesecret’,
generateToken(userid){
let tokenId = jwt.sign({‘uid’:userid},this.secret,
{expiresIn:’1h’});
console.log(“Token Id is “,tokenId);
return tokenId;
},
verifyToken(tokenId)
{
let decoded = jwt.verify(tokenId,this.secret);
if(decoded && decoded.uid){
console.log(“Decoded “,decoded.uid);
return true;
}
else{
console.log(“Invalid Token “);
return false;
}
}
}
// Testing code
// var tokenNumber = token.generateToken(‘ram’);
// token.verifyToken(tokenNumber);

Integrate JSON Token with PassPort

Calling Done of Passport Call Back to Call the CallBack URL

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-googleoauth20’);
const config = require(‘./config’);
var google = new GoogleStrategy({
clientID:config.clientID,
clientSecret:config.clientSecret,
callbackURL:config.callbackURL
// key ,value for google Strategy
},(accessToken, refeshToken, profile, done)=>{
console.log(“I Will Call “);
done(null, profile);
});
passport.use(google);// it is like app.use
module.exports = passport;

Making Session False and get the result from the request.user and also generating the JWT Token

const express = require(‘express’);
const router = express.Router();
const passport = require(‘passport’);
const jwt = require(‘../utils/token’);
router.get(‘/auth’,passport.authenticate(‘google’,{scope: [‘profile’,’email’],session:false}));
router.get(‘/auth/cb’,passport.authenticate(‘google’,
{session:false}), (request,response)=>{
  console.log(‘Request ‘,request.user);
let tokenId =
jwt.generateToken(request.user.email);
response.set({‘content-type’:’text/html’});
response.send(`${request.user.emails[0].value}
<img src=”${request.user.photos[0].value}”/>

Name is ${request.user.displayName} Token Id
is ${tokenId}`);

});
module.exports = router;

Sign Up and Start Learning