Express Passport.js不会在会话

时间:2017-12-07 20:23:12

标签: node.js express session cors passport.js

我在端口3000上运行Express应用程序。前端在端口80上运行,因此这是一个CORS应用程序。用户存储在SQL Server数据库中。我使用护照作为本地策略的认证方法以及快速会话中间件。该应用程序是单页面应用程序,发送到服务器的所有请求都是通过ajax完成的。用户登录页面并发送凭据,如果验证成功,则应将userID以及用户名和FullNmae持久保存到会话中。

我有很多问题:主要是登录后,express将使用护照的用户名和其他数据保存到新会话中,并返回一个html片段来替换页面上的body标签。但是,为了测试用户对象是否仍然存在,我调用/ create-user路由并且它说用户对象不在那里。此外,新会话从每个请求开始(我检查日志并查看每次显示不同的会话ID)。不仅如此,但有一次我能够在浏览器中看到会话cookie,但我再也看不到它了。我试着回到可以看到cookie的地方,但它仍然没有出现!

我几个小时都不知所措,无法弄清楚为什么没有调用deserializeUser,也没有为什么数据不会被持久化。我哪里错了?

注意:省略了一些明显的代码(app.listen(),require语句等)

/* ------ CONFIGURATIONS ------ */
const app = express();
const mssqlConfig = JSON.parse(fs.readFileSync("mssql-config.json", "utf8"));
passport.use(new LocalStrategy(
    function loginAuthentication(username, password, done) {
        let connPool = new mssql.ConnectionPool(mssqlConfig);
        connPool.connect(error => {
            if (error) {console.log(error); return done(error);}
            ps = new mssql.PreparedStatement(connPool);
            ps.input('username', mssql.NVarChar(20));
            ps.input('password', mssql.NVarChar(50));
            ps.prepare('SELECT FullName, fldLoginName, fldEmployeeID, fldPassword FROM tblEmployees WHERE fldLoginName = @username AND fldPassword = @password;', error => {
                if (error) {console.log(error); return done(error);}
                ps.execute({username, password}, (error, result) => {
                    if (error) {console.log(error); return done(error);}
                    console.log(result);
                    if (result.recordset.length == 0) {
                        return done(null, false, {message: "There is no user with those credentials!"});
                    } else if (result.recordset[0].fldLoginName != username || result.recordset[0].fldPassword != password) {
                        return done(null, false, {message: "Username or password is incorrect!"})
                    } else {
                        return done(null, {
                            ID: result.recordset[0].fldEmployeeID,
                            username: result.recordset[0].fldLoginName,
                            fullName: result.recordset[0].FullName
                        });
                    }
                    ps.unprepare(error => console.log(error));
                });
            });
        });
    }
));
passport.serializeUser((user, done) => {
    done(null, JSON.stringify(user));
})
passport.deserializeUser((user, done) => {
    console.log(user);
    done(null, JSON.parse(user));
});

/* ----- MIDDLEWARE ------ */
app.use(function allowCrossDomain(request, response, next) { // CORS
    // intercept OPTIONS method
    response.header('Access-Control-Allow-Credentials', true);
    response.header('Access-Control-Allow-Origin', request.headers.origin);
    response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    response.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    response.header('Access-Control-Max-Age', '60');
    if ('OPTIONS' == request.method) {
        response.sendStatus(200);
    } else {
        next();
    }
});
app.use(bodyParser.json());
app.use(session({
    secret:"long string of characters",
    name:'officetools-extensions',
    saveUninitialized:false,
    resave:false,
    cookie:{secure:false, httpOnly:true, maxAge:86400000, domain:"http://officetools-extensions"},
    store: new MemoryStore({checkPeriod:86400000})
}));
app.use(passport.initialize());
app.use(function checkRestrictedURL(request, response, next){
    console.log(request.url);
    if (!request.url.match(/^\/login$/g)) {
        console.log("passed");
        passport.session()(request, response, next);
    } else {
        next();
    }
});

/* ------ ROUTES ------ */
app.post('/login', bodyParser.urlencoded({extended:false}), (request, response, next) => { 
    passport.authenticate('local', {session:true}, (error, user, info) => {
        if (error) { error.status = 500; return next(error); }
        if (info) { let err = new Error(info.message); err.status = 400; return next(err);}
        if (!user) { return response.status(401).send("User could not be logged in!"); }
        console.log(request.sessionID);
        console.log(user);
        console.log(request.session);
        request.logIn(user, function loginCallBack(error) {
            if (error) { error.status = 500; return next(error);}
            console.log("after login", request.session);
            console.log(request.isAuthenticated());
            return response.sendFile(path.join(__dirname + "/templates/barcodes.html"));
        })
    })(request, response, next);
});
app.get("/current-user", (request, response, next) => {
    console.log(request.user, request.session);
    console.log(request.sessionID);
    console.log(request.isAuthenticated());
    if (request.user) { 
        response.header("Content-Type", "application/json");
        return response.send(request.user);
    }
    else { return response.status(401).send("There is no user currently logged in!"); }
});

1 个答案:

答案 0 :(得分:0)

我明白了。我只需删除会话设置上的域属性。这使它发挥作用。