express session is not working with vuejs and axios - node.js

Session initialize in express.js also used passport.js for local-authentication which is working fine. But the session/cookie is not working
app.use(serveStatic(__dirname + '../../dist'));
mongoose.connect(config.database, function(err){
if(err) console.log(err);
console.log('Connected to DB');
})
app.use(cors({
origin:['http://localhost:8080'],
credentials: true // enable set cookie
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({ 'extended': 'false' }));
// required for passport
require('./config/passport')(passport); // pass passport for configuration
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
// session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
Get request with axios is below
axios.get(this.url + '/user', {withCredentials: true})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e)
})

Refer tutorial to store sessions or cookies using passport.js and express.js
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
instead of this try:
app.use(express.session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.session());

Related

MongoStore, Atlasdb return the mongoUrl and ClientPromise

I am getting error while trying to save session on mongodb. Here is my code.
//MIDDLEWARE FUNC
app.use(methodOverride('_method',{methods: ['POST','GET']}))
app.use(Express.static(path.join(__dirname, 'public')))
app.use(Express.urlencoded({extended:true}))
app.use(Express.json())
app.use(session({
secret: 'my_keyboard_cat',
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: process.env.DB_URI,
dbName: 'sessions'
})
}))
app.use(flash())
app.use((req,res,next) => {
res.locals.flashMessages = req.flash()
next()
})
and error is : Assertion failed: You must provide either mongoUrl|clientPromise|client in options
/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
throw new Error('Cannot init client. Please provide correct options')
Error: Cannot init client. Please provide correct options

Cookie-Session and Express-session both not being presists

here is my config:
const session = require('express-session');
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
}))
set in route:
req.session.challenge = makeCredChallenge.challenge;
req.session.user_name = body.user_name;
using in other route:
console.log('challange from session', req.session.challenge)
console.log('username from session', req.session.user_nam
e)
but its undefine in other routes where I'm using it

How to send cookies to client from node/express server?

I am having the hardest time sending cookies from my nodejs server to my browser. Below is my index.js (server side) code:
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
);
let port = process.env.PORT;
if (port == null || port == "") {
port = 5000;
}
mongoose.connect(process.env.ATLAS_URI).then(console.log("MongoDB Connection Success")).catch(err => console.log("MongoDB Connection Failed" + err))
app.use(session({
secret: 'random secret',
resave: false,
saveUninitialized: false,
// store: MongoStore.create({ mongoUrl: process.env.ATLAS_URI }),
cookie: {
expires: 7 * 24 * 6 * 60 * 1000,
secure: false,
},
}));
app.use(cookieParser())
app.use(passport.initialize())
app.use(passport.session())
app.use("/auth", auth)
I know a cookie is being created when i authenticate a user because if i uncomment out the store in app.use(session({...}) i see session IDs and cookies in my mongodb. But how can I send it to the browser?
try this config for the session options.
my version of express-session is "^1.17.2"
app.use(session({
name: 'random name',
resave: false,
saveUninitialized: false,
secret: 'random secret',
store: MongoStore.create({
mongoUrl: config.DatabaseUrl,
ttl: 14 * 24 * 60 * 60 // = 14 days. Default
})
}));
if this config does not work, check your passport authenticate function that set session true like the below example :
passport.authenticate('local.register', {session: true}, (err, user): void => {
// When res has an Error
if (err) return res.redirect('/auth/register');
return res.redirect('/');
})(req, res);

passport does not set the cookie

if i open express and react server in localhost, it works well. but if i open express server in aws(http), the cookie is not set.
here is my express index.ts code.
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: sessionSecret,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
sameSite: "none",
},
})
);
app.use(cors({ origin: frontendOrigin, credentials: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use("/", router);
app.listen(8000, () => {
console.log("Server has been started...");
});
i tried remove cookie options in express-session, origin: true and origin: false in cors.
and i fetch like this
const res = await fetch(`${backend}/api/profile`, {
credentials: "include",
});
why it only works in localhost? ofc i opened aws port 8000.

Res header contaisn set Cookie but browser isn't storing it

I'm using express-session to store session cookie. I can see Set-Cookie connect.ssid under the response header but for some reason it is not getting stored in the cookie.
I'm wondering if this is a CORS issue, my app file looks like this. Should I change something here to make it work.
const session = require('express-session');
const config = require('config');
var MemoryStore = require('memorystore')(session);
module.exports = function (app) {
// app.use(
// session({
// secret: 'key sign',
// resave: false,
// saveUninitialized: false
// })
// );
app.use(express.json());
app.use(cors({ credentials: true }));
enter code here
app.set('trust proxy', 1);
app.use(
session({
saveUninitialized: false,
cookie: { maxAge: 86400000 },
store: new MemoryStore({
checkPeriod: 86400000
}),
resave: false,
cookie: { secure: false },
secret: config.get('sessionStorage')
})
);
app.use('/api/users', users);
Here is how I fixed this.
Add SSL to both frontend and backend.
If it is self-signed, ensure browser trust it. For example, if you're using mac, go to keychain, select specific certificate and select always trust option.
Restart the system. Only then SSL will be properly set otherwise there would still be insecure badge in the navigations.

Resources