I have 2 web application in same IP and different port:
app1 = (site.com) -> 66.88.66.88:5000
app2 = (login.site.com) -> 66.88.66.88:5001
I`m using Nginx and set 2 proxy for these 2 application. The users have to login in to app1 and system will set a session for logged in user. after that system will redirect user to app2 and I need access to logged in user session in appp2.
I store my session in mongodb in same collecton that both apps has access to that.
My problem is I can`t have access to loggedin user session in app2.
This is my session settings:
app1:
const MongoStore = require('connect-mongo')(session);
mongoose.Promise = require('bluebird');
const connection = mongoose.createConnection(config.dbhost, function(err){
if(err){
console.log(err);
} else {
console.log('connected to the database successfuly.');
}
});
/* Session config */
var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
app.use(session({
secret: config.secureHasherKey ,
resave: true,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
domain: 'site.com',
path: '/',
expires: expiryDate
},
store: new MongoStore({ mongooseConnection: connection })
}));
app2:
const MongoStore = require('connect-mongo')(session);
mongoose.Promise = require('bluebird');
const connection = mongoose.createConnection(config.dbhost, function(err){
if(err){
console.log(err);
} else {
console.log('connected to the database successfuly.');
}
});
/* Session config */
var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
app.use(session({
secret: config.secureHasherKey ,
resave: true,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
domain: 'login.site.com',
path: '/',
expires: expiryDate
},
store: new MongoStore({ mongooseConnection: connection })
}));
And this is my CORS settings:
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma,
Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
return next();
});
How can I find the problem?
Related
I have been developing a simple login system and trying to deploy it on a production server. The express session works perfectly fine in localhost but when it comes to the production server or cross-origin it sends a new session in every request.
Server Codes:
const express = require('express');
const app = express();
const path = require('path');
const mysql = require('mysql');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
const bcrypt = require('bcryptjs');
require('dotenv').config();
const cors=require("cors");
const bodyparser = require("body-parser")
app.use(express.json())
app.use(bodyparser.urlencoded({extended: true}))
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
var db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME
});
db.connect((err) => {
if(err) {
console.log('error when connecting to db: ', err);
throw err;
}
});
const sessionStore = new MySQLStore({
expiration : (365 * 60 * 60 * 24 * 1000),
endConnectionOnClose: false,
}, db);
app.use(session({
key: 'fsasfsfafawfrhykuytjdafapsovapjv32fq',
secret: 'abc2idnoin2^*(doaiwu',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: (365 * 86400 * 1000),
httpOnly: false,
secure: false,
sameSite: 'none'
}
}));
app.post('/isLoggedIn', (req, res)=>{
// req.session.destroy();
if(req.session.userID || req.session.userID == 0) {
let cols = [req.session.userID];
db.query('SELECT * FROM user WHERE user_id = ? LIMIT 1',cols, (err, data, fields) => {
if(data && data.length === 1) {
res.json({
success: true,
first_name: data[0].first_name,
email: data[0].email,
type:data[0].type,
});
return true;
}else {
res.json({
success: false,
});
}
});
}else {
res.json({
success: false
})
}
});
API request:
let res = await fetch("https://hotel-network-manager1.herokuapp.com/isLoggedIn", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
mode:'cors'
});
I have read many posts and documentation but couldn't solve the issue. You can even check the server running in Heroku in the above URL of the fetch API. When using this same server running on the localhost it works perfectly fine which means this has something to do with CORS. Does anyone has any idea what I'm missing here.
I'm using express-session with redis in my NodeJS Backend.
let redisClient = redis.createClient(6380, process.env.REDISCACHEHOSTNAME, {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
app.use(session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: process.env.secret,
resave: true,
cookie: {
maxAge: 1 * 1 * 60 * 60 * 1000
}
}));
On login I store some user details in the session:
req.session.user = result;
And I build a middleware, which log my current session and refresh it on each request:
isOnline = (req, res, next) => {
console.log(req.session);
if (!req.session.user) {
return res.status(401).json({ result: 'Keine Session vorhanden', status: 'failure' });
}
req.session.touch();
next();
};
The extending of my cookie is working well. The cookie expiration datetime is everytime reset to 60 minutes from the request time. Which I can see by the console.log:
Session {
cookie: {
path: '/',
_expires: 2022-03-07T18:46:30.727Z,
originalMaxAge: 120000,
httpOnly: true
},
user: { ... }
}
The issue is, that my user data are lost after 60 minutes. So the cookie itself refreshs, but not the data. So how I can avoid this?
I have a problem with express-session. When I try to login I have to save my userdata in cookies and after redirect get it on home page. Now after redirect my cookie is clearing and I have default cookie without some data
const authRoute = require('./routes/auth')
mongoose.connect(
process.env.DB_CONNECT,
{ useUnifiedTopology: true, useNewUrlParser: true },
() => {
console.log('Connected to DB')
});
//Middleware
app.use(express.json())
app.use(cors())
app.use(session({
name: 'sid',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
secret: process.env.SESS_SECRET,
cookie: {
maxAge: 1000 * 60 * 60 * 2,
sameSite: true,
secure: false
}
}))
app.use('/api/user', authRoute)
Routes file
router.get('/login', (req, res) => {
console.log(req.session);
if (req.session.user) {
res.status(200).send(req.session.user)
} else res.status(403).send({ error: 'You need to login first' })
})
router.post('/login', async (req, res) => {
...
req.session.user = { id: user._id, username: user.name, email: user.email }
req.session.save()
//CREATE AND ASSIGN TOKER
const token = jsw.sign({ _id: user._id }, process.env.TOKEN_SECRET)
res.header('auth-toker', token).send(user)
})
Try disabling the Windows Defender or other anti virus software. Those may not allow the connection to go through
I use express.js and React. After success login I store user_id in session but after 2-3min session is lost and when I refresh page they log out me.
Here is my server.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host',
user : 'user',
password : 'password',
database : 'database',
pool : { maxConnections: 50, maxIdleTime: 30},
});
connection.connect(function(error){
if(!!error){
console.log('error');
}else{
console.log('Connected');
}
})
//pluginy
var bodyParser = require('body-parser');
var express = require('express');
var session = require('express-session');
var app = express();
//ustwienia
app.use(bodyParser()); //przesylanie danych w req.body
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'v8bRRj7XVC6Dvp',
saveUninitialized: true,
resave: true,
cookie: {secure: true}
}));
app.use('/static', express.static(__dirname + '/src'));
app.use('/dist', express.static(__dirname + '/dist'));
app.use('/php', express.static(__dirname + '/php'));
app.set('views', __dirname + '/views');
app.set('view engine','pug');
function checkAuth(req, res, next) {
console.log('User id: '+req.session.user_id);
if (!req.session.user_id) {
if(req.route.path=='/'){
res.render("indexNotLogin",{title:''});
}else{
res.send('You are not authorized to view this page');
}
} else {
next();
}
}
//roots
//index
app.get('/', checkAuth, function(req, res){
res.render("index",{title:''});
})
//funkcje
app.get('/funkcje', function(req, res){
res.render("funkcje",{title:''});
})
//trylogin
app.post('/trylogin', function(req, res){
var username = req.body.name;
var password = req.body.password;
connection.query("SELECT * FROM user WHERE username='"+username+"' AND pass='"+password+"' LIMIT 1", function(error, rows,fields){
//callback
if(!!error){
console.log('error in query');
}else{
if(rows.length){
console.log(rows[0].id)
req.session.user_id = rows[0].id;
res.redirect('/');
}else{
res.send('user dont exist')
}
}
})
})
app.listen(3000,'0.0.0.0', function(){
console.log('Port: 3000')
})
after form submit I do function /trylogin and eveything work fine, req.session.user_id = rows[0].id is user_id, but why session is lost so fast ?
You can increase your session time by using maxAge option in session middleware:
app.use(session({
secret: 'v8bRRj7XVC6Dvp',
saveUninitialized: true,
resave: true,
cookie: {maxAge:900000} //here ,15 min session time
}));
I solved this issue by using express-mysql-session package.
//import
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
let options = {
host: process.env.hostNameDB,
port: 3306,
user: process.env.userNameDB,
password: process.env.passwordDB,
database: process.env.databaseName,
expiration: 1000 * 60 * 60 * 24,
clearExpired: true,
checkExpirationInterval: 1000 * 60 * 60 * 24, //per day db cleaning
};
let sessionStore = new MySQLStore(options);
app.use(session({
key: 'session_cookie_name',
secret: 'session_cookie_secret',
store: sessionStore,
resave: false,
saveUninitialized: false,
}));
By using this package you can store your session data properly and then it will delete the data from DB when checkExpirationInterval is crossed.
I am Using expression-session and express-mysql-session for storing
in database but on every ajax returns new session id.
For more info calling from http only. This issue is not coming when I disable
security of browser.
var express = require('express'); var mysql = require('mysql'); var
jwt = require('jsonwebtoken'); var
session=require('express-session'); var MySQLStore =
require('express-mysql-session')(session);
var options = { host: 'localhost',// Host name for database
connection. port: 3306,// Port number for database connection. user:
'root',// Database user. password: '',// Password for the above
database user. database: 'node',// Database name.
checkExpirationInterval: 900000,// How frequently expired sessions
will be cleared; milliseconds. expiration: 1512671400000,// The
maximum age of a valid session; milliseconds. createDatabaseTable:
true,// Whether or not to create the sessions database table, if one
does not already exist. connectionLimit: 10,// Number of connections
when creating a connection pool schema: { tableName: 'sessions',
columnNames: { session_id: 'session_id', expires: 'expires', data:
'data' } } };
var connection = mysql.createConnection(options); // or
mysql.createPool(options); var sessionStore = new MySQLStore({}/*
session store options */, connection); var router =
express.Router();
router.use(session({ name: 'session_cookie_name', secret:
'session_cookie_secret', store: sessionStore, resave: false,
saveUninitialized: true, cookie: { path: '/', httpOnly: false,
secure: false, maxAge: 365 * 24 * 60 * 60 * 1000 } }));
router.get('/session', function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin,
X-Requested-With, Content-Type, Accept"); res.send(req.sessionID);
});
-
This issue is not coming when i disable security of browser
secure: true means your cookie is only transmitted over https doc.
So when accessing over http, the browser doesn't send the cookie, and the server thinks it's a new session.