I’m building an app with Vue, connecting through Axios to an API made with express.
I’m trying to use express-session to manage login sessions and auth. On my localhost it works great, but when I tried to use it from the site hosted on heroku, it breaks. The middleware that checks whether the session has an usuario
property blocks the call.
I’m pretty sure it has to do with https instead of http. I tested it on localhost https with some generated credentials and it broke the same way.
The endpoint for login is quite long, but basically checks if the password you gave it is correct, and if it is, it sets req.session.usuario
to an object with some user data. After that, when I check again for the session, usuario
is not set.
The CORS middleware:
const cors = require("cors");
const whitelist = ["https://localhost:8080", "https://hosted-client.herokuapp.com"];
const corsOptions = {
credentials: true,
origin: (origin, callback) => {
if (whitelist.includes(origin))
return callback(null, true);
//callback(new Error("CORS error"));
callback(null, true);
},
};
module.exports = cors(corsOptions);
The session middleware:
const Redis = require("ioredis");
const connectRedis = require("connect-redis");
const session = require("express-session");
const RedisStore = connectRedis(session);
const redisClient = new Redis(
process.env.REDIS_PORT,
process.env.REDIS_HOST,
{password: process.env.REDIS_PASSWORD}
);
module.exports = session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SECRET,
saveUninitialized: false,
resave: process.env.STATE_ENV === "production",
proxy: true,
cookie: {
secure: process.env.STATE_ENV === "production",
httpOnly: true,
sameSite: "none",
// maxAge: 1000 * 60 * 30, // 30 minutos
},
});
A simple test auth middleware:
module.exports = function (req, _, next) {
if (!req.session || !req.session.usuario) {
const err = new Error("No se encontró una sesión");
err.statusCode = 401;
next(err);
}
next();
}
The Axios instance on the client:
require("dotenv").config();
import axios from "axios";
export default axios.create({
baseURL: process.env.VUE_APP_API,
headers: {
"Content-type": "application/json",
},
withCredentials: true,
});
I’m not sure if that’s enough info, if not let me know.