19

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.

I understood the pro/con and basic overview of how JWT works. I learned it from the following source.

  1. https://medium.com/@rahulgolwalkar/pros-and-cons-in-using-jwt-json-web-tokens-196ac6d41fb4
  2. https://scotch.io/tutorials/the-ins-and-outs-of-token-based-authentication
  3. https://scotch.io/tutorials/the-anatomy-of-a-json-web-token
  4. https://auth0.com/blog/cookies-vs-tokens-definitive-guide

/

No JWT 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);

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

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);

The code return done(null, profile.id); // that is being serialized(added in session) is the problem. What should I replace it so that I don't have to use sessions? I want to replace it with JWT.

2
  • Is there no way to create JWT with passportjs?
    – sdfdsf sdf
    Commented Oct 30, 2017 at 3:38
  • can someone please refer me good jsonwebtoken nodejs examples?
    – sdfdsf sdf
    Commented Oct 30, 2017 at 5:19

5 Answers 5

14

https://www.sitepoint.com/spa-social-login-google-facebook/

basically after google authentication is done, you create a jwt for the user.

// src/index.js
function generateUserToken(req, res) {
  const accessToken = token.generateAccessToken(req.user.id);
  res.render('authenticated.html', {
    token: accessToken
  });
}

app.get('/api/authentication/google/start',
  passport.authenticate('google', { session: false, scope: 
  ['openid', 'profile', 'email'] }
));
app.get('/api/authentication/google/redirect',
  passport.authenticate('google', { session: false }),
  generateUserToken
);
3
  • 2
    After that i still get Failed to serialize user into session
    – ValRob
    Commented May 9, 2020 at 20:40
  • 1
    @ValRob Have you included { session: false } on the passport.authenticate second parameter?
    – Owl
    Commented Jul 1, 2020 at 11:54
  • @ValRob i have the same problem, this is happening when i use the openid instead of Oauth2 package, make sure you use the correct package: npm install passport-google-oauth const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
    – Flamingo
    Commented Apr 14 at 21:53
8

After a long time spent trying to find a workaround, I finally came across this. The best option thus far, works perfectly for me.

app.get('/auth/google/callback',  
  passport.authenticate('google', 

  { failureRedirect: '/', session: false }), (req, res) => {

    const jwt = createJWTFromUserData(req.user);
    const htmlWithEmbeddedJWT = `
    <html>
      <script>
        // Save JWT to localStorage
        window.localStorage.setItem('JWT', '${jwt}');
        // Redirect browser to root of application
        window.location.href = '/';
      </script>
    </html>
    `;

    res.send(htmlWithEmbeddedJWT);
});
5
  • 5
    How do you do this when you have front end and back end running on two different ports? (Say, front end on :3000 and node on :5000) Commented May 1, 2020 at 19:10
  • 2
    @davyCode False. The front end and back end are not on the same port.
    – zicxor
    Commented May 23, 2020 at 18:00
  • is localStorage suitable for auth token?
    – mercury
    Commented Jul 1, 2021 at 3:01
  • @HossamMaher yes you can store auth token in localStorage
    – davyCode
    Commented Sep 24, 2021 at 19:15
  • @davyCode what if you have an API working as a web service so not always request will be coming from a website. Commented Jan 3 at 21:38
4

This can be achieved by opening the google auth screen in a new window and writing the JWT back using window.postMessage().

App:

const Login = () => {
    const setToken = function(e) {
    if (
      e.origin === origin &&
      e.data &&
      e.data.command === 'token-ready' &&
      e.data.info &&
      e.data.info.token
    ) {
      localStorage.setItem('jwt', e.data.info.token);

      e.source.postMessage(
        {
          command: 'info',
          info: {
            complete: true,
          },
        },
        e.origin
      );
    }
  };

  
  window.addEventListener('message', setToken, false);

  const login = () => {
    window.open(loginUri);
  };

  return (<button onClick={login}>Login</button>
}

Server Response:

const html = `
  <!DOCTYPE html>
  <html>
    <head>
      <title>Authenticated</title>
    </head>
    <body>
      Authenticated successfully.
      <script type="text/javascript">
        window.addEventListener("message", function(e) {
          console.dir(e)
          if (e.origin === "${postBackUri}" && e.data && e.data.info && e.data.info.complete) {
              window.close();
          }
        }, false);
      
        opener.postMessage({
          command: "token-ready",
          info: {
            token: "${token}",
          },
        }, "${postBackUri}");
      </script>
    </body>
  </html>
`;

return res.send(html);
2

This will work for you

app.get('/google',passport.authenticate('google', { scope: ['profile'] }));

// callback google 
app.get(
  '/google/callback',
  passport.authenticate('google', { session: false, failureRedirect: '/login/failed' }),
  (req, res) => {
    // generate new access token
    const acc = GenerateAccessToken(req.user);
    res.cookie('au_ac',acc,{httpOnly:true});
    return res.redirect(CLIENT_URL)
  }
);

And here to verify the token

app.get('/is/authenticated', async(req, res) => {
  const { au_ac } = req.cookies;
  if (!au_ac) return res.json({ authenticated: false });

  try {
    const user = await Verify_Access_Token(au_ac);
    return res.json({ user, authenticated: true })
  } catch(err) {
    return res.status(401).json({ authenticated: false })
  }
});

This's a simple example your app should have Refresh Token also.

-1

Take a look at Passport-JWT. As they say, this module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.

1
  • The main problem is it is not handleable using http clients (not browser) because of popup and redirections. It seems no way except the one @davyCode said, or set a server side cookie. Actually passport must have create auth link but it have not. Commented Aug 26, 2020 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.