如何使passportjs google login oauth与JWT一起使用,而不是通过序列化/反序列化方法创建会话?

sdf*_*sdf 11 node.js jwt google-oauth passport.js passport-google-oauth

如果我添加创建会话的序列化/反序列化passportjs方法,下面的代码将完美运行。我正在努力创建 Json Web 令牌,而不是会话。任何教程、建议或清晰的示例将不胜感激。我使用 nodejs。

我了解 JWT 工作原理的优点/缺点和基本概述。我从以下来源了解到它。

  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

/

没有 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;


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);
Run Code Online (Sandbox Code Playgroud)

JWT 代码尝试。问题是我需要添加序列化/反序列化,我不想这样做,因为我不想使用会话。我想要 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);
Run Code Online (Sandbox Code Playgroud)

代码return done(null, profile.id); // that is being serialized(added in session)是问题。我应该用什么替换它以便我不必使用会话?我想用 JWT 替换它。

小智 9

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

基本上在谷歌身份验证完成后,您为用户创建一个 jwt。

// 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
);
Run Code Online (Sandbox Code Playgroud)


dav*_*ode 8

经过很长时间寻找解决方法,我终于遇到了这个问题。迄今为止最好的选择,非常适合我。

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);
});
Run Code Online (Sandbox Code Playgroud)

  • 当前端和后端在两个不同的端口上运行时,如何做到这一点?(比如说,前端在:3000,节点在:5000) (5认同)
  • @davyCode 错误。前端和后端不在同一个端口。 (2认同)