简体   繁体   中英

sockiet.ion passport.js, express.js and authentication headers

My chrome extension was working perfectly until recently.

I originally received a error message of

required same site none and secure in the header

I then added to my express.session config,

 samesite:none, secure:true

Now instead of that error, I am unable to gain access to my website by login in with my chrome extension, which I believe is due to socket.io not maintaining the authentication cookie.

My express server is as below,

const config = require('../../config');

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, { wsEngine: 'ws' });
const mysql = require('mysql');
const expressSession = require('express-session');
const ExpressMysqlSessionStore = require('express-mysql-session')(expressSession);
const sharedsession = require('express-socket.io-session');
const path = require('path');

const utils = require('./utils');

// remove from header "X-Powered-By: Express"
app.disable('x-powered-by');

server.listen(config.serverParams.port, config.serverParams.address, () => {
    console.log(`Server running at http://${server.address().address}:${server.address().port}`);
});

/* DATABASE */
global.db = mysql.createConnection(config.db);
db.connect();
/* DATABASE */

/* SESSION */
const sessionStore = new ExpressMysqlSessionStore(config.sessionStore, db);
const session = expressSession({
    ...config.session,
    store: sessionStore,
});
app.use(session);
/* SESSION */

app.use(express.static(config.frontendDir));

app.get([
    '/signup',
    '/stats',
    '/pay',
], (req, res) => res.sendFile(path.join(`${config.frontendDir}${req.path}.html`)));

io.use(sharedsession(session, {
    autoSave: true
}));

io.on('connection', socket => {

    socket.use((packet, next) => {
        if (packet[0]) {
            console.log('METHOD:', packet[0]);
            const sessionData = socket.handshake.session.user;
            const noSessionNeed = [ 'login', 'signup', 'checkAuth' ].includes(packet[0]);
            let error;
            if ( ! sessionData && ! noSessionNeed) error = { code: -1, message: 'You need to login in extension!' };
            if (error) return next(new Error(JSON.stringify(error)));
            else next();
        }
    });

    const auth = require('./auth')(socket);
    socket.on('checkAuth', auth.checkAuth);
    socket.on('login', auth.login);
    socket.on('signup', auth.signup);
    socket.on('logout', auth.logout);

    const users = require('./users')(socket);
    socket.on('users.get', users.get);

    const sentiment = require('./sentiment')(socket);
    socket.on('sentiment.get', sentiment.get);
    socket.on('sentiment.set', sentiment.set);

    socket.on('disconnect', () => {

    });

});

And the config file is somewhat like this,

config.session = {
        // globals.config.express.sessionSecret
        resave: true,
        saveUninitialized: true,
        cookie: {
                maxAge: 86400000,
                /* FOR WORK ON LOCALHOST
                secure: true,
                sameSite: 'lax', */
                sameSite:"None",
                secure:true,
                domain: '.xx.xx',
        },

Here is how the authentication is done with the socket.io

const passport = require('passport');
/* PASSPORT */
require('./passport')(passport); // pass passport for configuration
/* app.use(passport.initialize());
app.use(passport.session()); */
/* PASSPORT */

const utils = require('./utils');

const bcrypt = require('bcrypt');
const saltRounds = 10;

module.exports = socket => {

    this.checkAuth = fn => {
        if (fn) fn();
    };

    this.login = (params, fn) => {
        passport.authenticate('local-login', (err, user) => {
            const response = {};
            if (user) {
                socket.handshake.session.user = user;
                socket.handshake.session.save();
                response.message = 'Your successful login!';
                response.data = {
                    id: user.id,
                    username: user.username,
                };
            }
            else if (err) {
                response.error = {
                    code: err,
                    message: ''
                };
                if (err == -1) response.error.message = 'Incorrect username or password!';
            }
            if (fn) fn(response);
        })({ body: params });
    },

    // socket.on('signup', (params, fn) => {
    this.signup = (params, fn) => {
        passport.authenticate('local-signup', (err, user) => {
            const response = {};
            if (user) {
                console.log('signup', user);
                response.message = 'Your successful signup!';
            }
            else if (err) {
                response.error = {
                    code: err,
                    message: ''
                };
                if (err == -1) response.error.message = 'User alreay exist!';
            }
            if (fn) fn(response);
        })({ body: params });
    };

    // socket.on('logout', fn => {
    this.logout = fn => {
        delete socket.handshake.session.user;
    };

    return this;

};

utils

module.exports = socket => {

    // socket.on('users.get', fn => {
    this.get = fn => {
        if (fn) {
            const response = {};
            response.data = {
                id: socket.handshake.session.user.id,
                username: socket.handshake.session.user.username,
            };
            fn(response);
        }
    };

    return this;

};

Would love to be able to solve this issue :P

Thanks!

这是通过使用 JWT 令牌解决的,与此分开,以解决 socket.io session.s 的问题

Maybe it has to do with the signup function? I think there's no sign up option for first-comers. Try making if (user) -> if (!user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM