如果会话安全性为真,则ExpressPassport无法设置req.user

时间:2019-02-20 02:55:32

标签: javascript node.js express-session

  

使用以下命令登录时,Passport无法创建req.user会话   谷歌

在这种情况下,我使用NODE_ENV = production和HTTPS。但是护照仍然无法创建req.user

我已经搜索了方法并得到了它:

cookie: { 
    secure:false,
    httpOnly: true,
    maxAge:keys.session.maxAge, // satu hari,
 }

我需要设置Secure = false,并且sameSite = false或req.user不会出现。 为什么会这样?即使我已经有HTTPS连接?

这是我的Server.js:

import express from 'express';
import bodyParser from 'body-parser';
import passport from 'passport';
import connection from './config/conn';
import { 
    CategoryRoutes,
    ProductRoutes,
    CartRoutes,
    AuthRoutes,
    TrackRoutes,
    AddressRoutes,
    ShippingRoutes,
    UIRoutes,
    LookbookRoutes,
    CheckoutRoutes,
    OrderRoutes,
    VoucherRoutes
} from './modules';
import session  from 'express-session';
// import csrf  from 'csurf'
import cors from 'cors'
import cookieParser  from 'cookie-parser'
// import cookieSession from 'cookie-session'
import passportSetup from './config/passport-setup';
import keys from './config/keys';
import uuidv4  from 'uuid/v4';
import UAparser  from 'ua-parser-js';
import { ensureSession } from './config/sessionCheck';
import path from 'path';

const app = express();
app.use(express.static('client/build'));
app.use(session({
    genid: function (req) {
        return uuidv4() // use UUIDs for session IDs
    },
    name:keys.session.name,
    secret: keys.session.secret,
    resave: false,
    saveUninitialized: true,
    rolling:true,
    cookie: { 
        secure:true,
        httpOnly: true,
        maxAge:keys.session.maxAge, // satu hari,
        sameSite:true,
     }

}));
 app.set('trust proxy', 1);

// app.use('/public',express.static(path.join(__dirname,'public')));
app.use(cookieParser());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


app.use(passport.initialize());
app.use(passport.session());

// app.use(csrf({ cookie: false }));

app.disable('x-powered-by');

app.use(cors({ origin: keys.origin.url }))





app.use(ensureSession,(req, res, next) => {
    res.header('X-XSS-Protection', '1; mode=block');
    res.header('X-Frame-Options', 'deny');
    res.header('X-Content-Type-Options', 'nosniff');
    res.header("Access-Control-Allow-Origin",keys.origin.url);
    console.log(req.user);
    next();
})

app.use('/api/', [
    CategoryRoutes, 
    ProductRoutes, 
    CartRoutes, 
    AuthRoutes, 
    TrackRoutes, 
    AddressRoutes, 
    ShippingRoutes, 
    UIRoutes,
    LookbookRoutes,
    CheckoutRoutes,
    OrderRoutes,
    VoucherRoutes
]);

app.post('/api/payment/notification',(req,res)=>{
    return res.status(200).json(req.body);
})
    // Set static folder

    app.get('*',(req,res)=>{

 res.sendFile(path.resolve(__dirname,'../', 'client', 'build', 'index.html'));
    })


const port = process.env.PORT || 40000;
app.listen(port, (err) => {
    if(err){
        console.log(err);
    }else{
        console.log(`Server running on port ! ${port}`);
    }

});

护照设置

import passport from 'passport';
import GoogleStrategy from 'passport-google-oauth20';
import FacebookStrategy from 'passport-facebook';
import keys from './keys';
import db from './conn';

passport.serializeUser((user, done) => {
    let tokenValue={
        providerId:user.providerId,
        token:user.token,
        user_id:user.id,
        provider:user.provider
    }
    done(null, tokenValue)
})
passport.deserializeUser((data, done) => {
    let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? and up.provider = ? and up.providerId = ? and up.token = ? and us.is_provider = 1`;
    db.query(querySelect,[data.user_id,data.provider,data.providerId,data.token], (err, ress) => {
        if(ress.length > 0){
            done(null, ress[0])
        }

    })

})

passport.use(
    new GoogleStrategy({
        //options for the google strategy
        callbackURL: 'https://..../api/auth/google/redirect',
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret
    }, (accessToken, refreshToken, profile, done) => {
        console.log(profile);
        let queryInsert = `INSERT INTO user set is_provider = 1, ?; INSERT INTO user_provider set user_id = (SELECT u.id from user as u order by id desc limit 1), ?;`;
        let queryFind = `SELECT 
        us.id,
        us.displayName,
        us.email,
        us.gender,
        up.providerId,
        up.token,
        up.provider,
        us.firstname,
        us.lastname,
        ui.birthday,
        ui.phone_number
        from user as us 
        left join user_provider as up on us.id = up.user_id 
        left join user_information as ui on us.id = ui.user_id
        where up.providerId = '${profile.id}' and up.provider = '${profile.provider}' and us.is_provider = 1`;

    let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? and up.provider = ? and up.providerId = ? and up.token = ? and us.is_provider = 1`;
        let user = {
            email: profile.emails[0].value,
        }
        if(profile.gender)user.gender = profile.gender;
        if (profile.displayName) user.displayName =profile.displayName;
        if(Object.keys(profile.name).length > 0){
            if(profile.name.familyName) user.lastname = profile.name.familyName;
            if(profile.name.givenName) user.firstname = profile.name.givenName;
        }

        let user_provider={
            provider:profile.provider,
            providerId:profile.id,
            token:accessToken
        }
        db.query(queryFind, (error, result) => {
            if(error) return done(error);
            if (result.length > 0) {
                return done(null, result[0]);
            }else{

                db.query(queryInsert, [user, user_provider], (err, ress, fields) => {
                    if (err) return done(err);
                    if (ress) {
                        db.query(querySelect, [ress[0].insertId, profile.provider, profile.id, accessToken],(err,ress)=>{
                            if (err) return done(err);
                            if(ress.length > 0){
                                return done(null, ress[0]);
                            }

                        })
                    }
                })
            }
        })







    })

);

路线

import { Router } from 'express';
import * as AuthController from './controller';
import passport from 'passport';
const routes = new Router();
routes.get('/auth/google',passport.authenticate("google",{
    scope: ["profile","email"]
}));


routes.get('/auth/google/redirect', passport.authenticate("google"), AuthController.loginGoogleRedirect);
routes.post('/auth/logout',AuthController.logout);


export default routes;

0 个答案:

没有答案