title: How can I make passportjs google login oauth work with JWT instead of creating session through serialize/deserialize method?
body: <p>The below code will works perfectly If I add the serialize/deserialize passportjs method, which creates a session. I am working to create Json Web  Token, not session. Any tutorial, suggestion or clear sample would be greatly appreciated.I use nodejs.</p>
  
  <p>I understood the pro/con and basic overview of how JWT works. I learned it from the following source.</p>
  
  <ol>
  <li><a href="https://medium.com/@rahulgolwalkar/pros-and-cons-in-using-jwt-json-web-tokens-196ac6d41fb4" rel="noreferrer">https://medium.com/@rahulgolwalkar/pros-and-cons-in-using-jwt-json-web-tokens-196ac6d41fb4</a></li>
  <li><a href="https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication" rel="noreferrer">https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication</a></li>
  <li><a href="https://scotch.io/tutorials/the-anatomy-of-a-json-web-token" rel="noreferrer">https://scotch.io/tutorials/the-anatomy-of-a-json-web-token</a></li>
  <li><a href="https://auth0.com/blog/cookies-vs-tokens-definitive-guide" rel="noreferrer">https://auth0.com/blog/cookies-vs-tokens-definitive-guide</a></li>
  </ol>
  
  <p>/</p>
  
  <p><strong>No JWT code</strong></p>
  
  <pre><code>var express = require("express"),
      path = require("path"),
      bodyParser = require("body-parser"),
      mysql = require("mysql"),
      connection = require("express-myconnection"),
      morgan = require("morgan"),
      app = express(),
  
      passport = require("passport"),
      GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
  
  
  app.use(passport.initialize());
  
  app.get("/", function(req, res) {
      res.sendFile(__dirname + "/public/main.html");
  });
  
  
  // #1
  passport.use(
      new GoogleStrategy({
              clientID: "32434m",
              clientSecret: "23434",
              callbackURL: "http://localhost:3000/auth/google/callback"
          },
          function(accessToken, refreshToken, profile, done) {
              process.nextTick(function() {
                  console.log("profile.id: " + profile.id);
                  return done(null, profile.id); // that is being serealized(added in session)
              });
          }
      )
  );
  
  // #1
  app.get("/auth/google",
      passport.authenticate(
          "google", {
              scope: ["profile", "email"]
          }));
  
  // #2
  app.get("/auth/google/callback",
      passport.authenticate("google", {
          failureRedirect: "/google_callback_fail",
          successRedirect: "/google_callback_success"
      })
  );
  
  app.get("/google_callback_success", isLoggedIn, function(req, res) {
      res.send("google_callback_success \n");
  });
  
  function isLoggedIn(req, res, next) {
      console.log("isLoggedIn req.user: " + req.user);
  
      if (req.isAuthenticated()) {
          console.log("isAuthenticated TRUE");
          return next();
      }
      res.redirect("/notloggedin");
  }
  
  app.get("/notloggedin", function(req, res) {
      console.log("req.user: " + req.user);
      res.json("not loggedin");
  });
  
  app.get("/google_callback_fail", function(req, res) {
      res.json("the callback after google DID NOT authenticate the user");
  });
  
  
  app.listen(3000);
  </code></pre>
  
  <p><strong>JWT code attempt. The problem is I need to add serialize/deserialize, which I don't want to, since, I don't want to use session. I want JWT</strong></p>
  
  <pre><code>var express = require("express"),
      path = require("path"),
      bodyParser = require("body-parser"),
      mysql = require("mysql"),
      connection = require("express-myconnection"),
      morgan = require("morgan"),
      app = express(),
  
      passport = require("passport"),
      GoogleStrategy = require("passport-google-oauth").OAuth2Strategy,
  
      jwt = require('jsonwebtoken'),
      passportJWT = require("passport-jwt"),
      ExtractJwt = require('passport-jwt').ExtractJwt,
      JwtStrategy = require('passport-jwt').Strategy;
  
  
  var jwtOptions = {};
  jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  jwtOptions.secretOrKey = 'secret';
  
  
  
  app.use(passport.initialize());
  
  app.get("/", function(req, res) {
      res.sendFile(__dirname + "/public/main.html");
  });
  
  
  // #1
  passport.use(
      new GoogleStrategy({
              clientID: "s-s.apps.googleusercontent.com",
              clientSecret: "23redsf",
              callbackURL: "http://localhost:3000/auth/google/callback"
          },
          function(accessToken, refreshToken, profile, done) {
              process.nextTick(function() {
  
                  console.log("\nprofile.id: " + profile.id);
  
                  return done(null, profile.id); // that is being serealized(added in session)
              });
          }
      )
  );
  
  // #1
  app.get(
      "/auth/google",
      passport.authenticate(
          "google", {
              scope: ["profile", "email"]
          }
      )
  );
  
  // #2
  app.get(
      "/auth/google/callback",
      passport.authenticate("google", {
          failureRedirect: "/google_callback_fail",
          successRedirect: "/google_callback_success"
      })
  );
  
  app.get("/google_callback_success", isLoggedIn, function(req, res) {
      var payload = { id: user.id };
      var token = jwt.sign(payload, jwtOptions.secretOrKey);
      var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
          console.log('payload received', jwt_payload);
          console.log('jwt_payload.id: ' + jwt_payload.id);
      });
      passport.use(strategy);
      res.send("google_callback_success \n" + 'token: ' + token);
  });
  
  function isLoggedIn(req, res, next) {
      console.log("isLoggedIn req.user: " + req.user);
  
      if (req.isAuthenticated()) {
          console.log("isAuthenticated TRUE");
          var payload = { id: user.id };
          var token = jwt.sign(payload, jwtOptions.secretOrKey);
          console.log('token: ' + token);
          return next();
      }
      res.redirect("/notloggedin");
  }
  
  app.get("/notloggedin", function(req, res) {
      console.log("req.user: " + req.user);
      res.json("not loggedin");
  });
  
  app.get("/google_callback_fail", function(req, res) {
      res.json("the callback after google DID NOT authenticate the user");
  });
  
  app.get("/logout", function(req, res) {
      console.log("logged out");
      req.logout();
      res.redirect("/logout");
  });
  
  app.listen(3000);
  </code></pre>
  
  <p>The code <code>return done(null, profile.id); // that is being serialized(added in session)</code> is the problem. What should I replace it so that I don't have to use sessions? I want to replace it with JWT.</p>