简体   繁体   中英

Session-cookie not set on the next request - Express.js

I'm trying to set a cookie when logging in, but the cookie doesn't seem to follow to the next request. What am I doing wrong? (Sorry if nooby question, quite new to express).

The app.js

let express = require("express");
let session = require("express-session");
let bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: false,
    cookie: { secure: true }
}));

The router

router.route("/login")
    .get(function(request, response) {

        response.render("../views/partials/login");
    })

    .post(function(request, response) {

        let username = request.body.username;
        let password = request.body.password;

        User.findOne({user: username}, function(err, user) {
            if (err) {
                // Some error handling
            }

            // test password if matching
            if (user !== null) {
                user.comparePassword(password, function(err, match) {
                    if (err || !match) {
                        console.log("The user could not be found")
                    }

                    request.session.Auth = { username: username, password: password };
                    response.redirect("/home");
                    response.end();
                });
            } else {
                // some error handling
            }
        });

    });

Then when I do the next request on "/home", the session cookie holds no value about the user( req.session.Auth returns undefined )

router.route("/home")
    .get(restrict, function(req,res) {

console.log(req.session.Auth) // -> undefined
        res.render("../views/home")
    });

Maybe I'm doing this wrong, but I can't understand why the request.session doesn't hold the Auth-value. Can somebody please help?

PS I do not want to use any modules to handle authorization, like passport etc.

What you're doing is not going to work.

I really recommend you use passport.js for authentication. It's very simple, and takes away a lot of the work you're doing now. Accessing the request object in this post request does nothing.

Please try this way.

First enabled cookie session in express

app.use(express.cookieParser('S3CRE7'));
app.use(express.cookieSession({
    key: 'app.key',
    secret: 'app.secret'
}));
app.use(app.router);

after enabling cookie session, you can get/set what ever property to request.session.

I think rest of your logic is fine.

Are you testing your app in HTTPS? If not, then you should initialize the express session without the cookie: { secure: true } property, as

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: false
}));

A secure cookie is a cookie that will only be sent when HTTPS is used.

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