javascript PassportJS身份验证设置#passportjs #cookiesession #nodejs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript PassportJS身份验证设置#passportjs #cookiesession #nodejs相关的知识,希望对你有一定的参考价值。

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');

const mongoose = require('mongoose');
const User = mongoose.model('users');

//what is passed in the `done` callback function(refer to `passport.use`), that will be the `user` data
//Step 2: this will be serialized and the id will be saved in a cookie.
passport.serializeUser((user, done) => {
    console.log('serialize passport. ID: ', user.id);
    done(null, user.id);
});

//Step 3: The cookie will be deserialized(in this case, the `ID`)
passport.deserializeUser((id, done) => {
    console.log('deserialize passport. ID: ',id);

    User.findById(id).then(user => {
        done(null, user);
    }).catch((e) => console.log(e));
});

//generic register for passport strategies
//Step 1: This particular strategy will be called if it's called inside passport.authenticate() -> in this case, it's `google`
passport.use(
    new GoogleStrategy({
        clientID: keys.googleClientID,
        clientSecret: keys.googleClientSecret,
        callbackURL: '/auth/google/callback' //note: we still need to specify this uri in Google API -> `Authorised redirect URIs`
    }, (accessToken, refreshToken, profile, done) => { //if the code is authenticated in route `/auth/google`, then this callback will be called
        const googleID = {googleId: profile.id};

        //this query is asynchronous and returns a promise. We need to run this one to determine whether the googleId already exists inside MongoDB database.
        User.findOne(googleID).then((existingUser) => {
            if (!existingUser) {

                //this one is asynchronous.
                new User(googleID) //this creates new model instance
                    .save() //this then saves the model instance in MongoDB. Call save() to persist it in MongoDB
                    .then((user) => {
                        done(null, user); //what is passed in 2nd argument will be used in passport.serializeUser() as `user` in 2nd argument
                    }); //this callback will then fetch the new user being created asynchronously and use it in your functions.
            } else {
                console.log('existing user');
                //1st parameter: if there's no issue, put `null`
                //2nd parameter: put the existingUser in it.
                done(null, existingUser); 
            }

            console.log('User checking complete..');
        });
    })
);
const express = require("express");
const mongoose =  require("mongoose");

//for managing cookies
const cookieSession = require('cookie-session');
const passport = require('passport');

const keys = require('./config/keys');
const app = express();

//30 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
const cookieSessionDuration = 30 * 24 * 60 * 60 * 1000;

//app.use adds configuration to an app when it is run. We use this to wire up `middleware`. Middlewares are small functions that can be used to modify `incoming requests` before they were sent to route handlers.
//we use cookieSession to set up a cookie-based authentication
app.use(
    cookieSession({
        maxAge: cookieSessionDuration,
        keys: [keys.cookieKey]
    })
);
//A middleware
app.use(passport.initialize());
//A middleware
app.use(passport.session());


require("./models/User");
//we just want to run everything inside passport.js file so we do it like this
require("./services/passport");
// const authRoutes = require('./routes/authRoutes');

mongoose.connect(keys.mongoURI);

require("./routes/authRoutes")(app);

//heroku injects environment variables. And we use that port to run our app
const PORT = process.env.PORT || 5000;
//instructs express to tell node that it wants to listen to traffic in port 5000
app.listen(PORT);
const passport = require("passport");

module.exports = app => {
  app.get(
    "/auth/google",
    //passport gets GoogleStategy as strategy when we specify `google` string
    passport.authenticate("google", {
      scope: ["profile", "email"] //scope specifies to google what access we want to have inside user's profile. Google has lists of scopes to be used in this array
    })
  );

  //passport gets GoogleStategy as strategy when we specify `google` string
  app.get("/auth/google/callback", passport.authenticate("google"));

  app.get('/api/current_user', (req, res) => {
    //cookie-session assigns the cookie generated in req.session. This will generate passport.user: "userId"
    //cookie-session library populates req.session
    // res.send(req.session);

    //passport is looking at req.session and pulls the data in deserializeUser where we turn user id into a user
    res.send(req.user);
  });

  app.get('/api/logout', (req, res) => {
    req.logout(); //req.logout is a function that is automatically attached by PassportJS. It gets the cookie that contains userId and kills that cookie

    res.send(req.user); //call this callback to send that the user is no longer logged in.
  });


};

以上是关于javascript PassportJS身份验证设置#passportjs #cookiesession #nodejs的主要内容,如果未能解决你的问题,请参考以下文章

使用 Passportjs 刷新页面后保持身份验证

如果用户通过一次身份验证,防止用户再次登录passportjs?

身份验证后使用 passportjs-google 重定向到原始页面(无会话)

如何设置PassportJS进行后端身份验证?

Nodejs和PassportJs:如果身份验证失败,则不会调用passport.authenticate后重定向中间件

Express Passportjs在路由器回调中未进行身份验证