Cookie not being sent to AWS ECS server from ReactJS - node.js

I am current deploying a MERN Stack application and have successfully deployed the backend api to http://44.198.159.229/. I am now trying to connect it to my client server which is still running on localhost:3000. However, I am running into a cookie related issue. I am receiving the cookie on my frontend from the backend express server, but upon making a get request an authenticated route the frontend is not sending the cookie back. In the network tag in google chrome I see that the cookie is instead filtered out. I have done countless research and browsed various posts but cannot seem to find the solution for this. It works when I check the api route manually in my browser but does not upon sending an axios request. It also works when I'm deploying the backend on my local server but I imagine because they are both on the same domain.
Here is my express configuration on the backend.
const corsOptions = {
credentials: true,
origin: "http://localhost:3000",
optionsSuccessStatus: 200,
};
// Express backend for web application
const app = express();
app.set("trust proxy", true);
/////////////////////////////////////////////////////// Middleware //////////////////////////////////////////////////
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(
session({
secret: "somethingsecretgoeshere",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: false,
secure: false,
maxAge: 10 * 60 * 100000,
sameSite: 'none'
},
})
);
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
passportConfig(passport);
app.use("/api", auth_routes);
app.use("/api", major_requirement_routes);
app.use("/api", user_course_routes);
export default app;
Here is the route at which I am making the get request to see if a user is authenticated
router.get("/auth/check", (req, res) => {
console.log(req.user)
console.log(req.cookies)
if (req.user) {
User.findOne({netId: req.user}, function (err, docs) {
if (err) {
console.log(err);
} else {
res.json({
auth: true,
user: req.user,
courseList: docs.courseList,
semesterList: docs.semesterList,
major: docs.major,
creditsApplied: docs.creditsApplied,
emailAddress: docs.emailAddress,
});
}
});
} else {
res.json({auth: false, id: null});
}
});
Here is my axios config
import axios from "axios";
const backend_url = "http://44.198.159.229:5000/api"
// const backend_url = "http://localhost:5000/api"
export default axios.create({
withCredentials: true,
baseURL: backend_url,
});
Here is my axios get request on the frontend
axios
.get("auth/check", { withCredentials: true,credentials: 'include',
})
.then(({ data}) => {
console.log(data)
if (data.auth) {
setIsAuthenticated(true);
setUser(data.user);
setCourseList(data.courseList);
setIsLoading(false);
} else {
setIsAuthenticated(false);
setCourseList(undefined);
setUser(undefined);
setIsLoading(false);
}
})
.catch(() =>
console.log(
"Something went wrong while trying to fetch your auth status."
)
);
}, []);

Okay so after a lot of research and playing around for a few days I have found a solution. I had to use a SSL and redirect traffic to an https server via AWS load balancing and set sameSite: None httpOnly: true, secure: true. I hope this helps someone else. This is because cookies can only be sent to cross origin sites that are secure. I also had to change my local host to run on https instead of http

Related

Why is the express session cookie not stored in the browser's cookie storage on production but is working on localhost/development? (express + react)

I have created a test app, my react app is deployed at vercel and my node express is deployed at render.com. I set the same domain on both to solve cross-site cookie problems (app.mydomain.online)(api.mydomain.online). Now no error is showing when I view the cookie in the header but still when I check the cookie storage it is still not stored or not being saved at the browser's cookie storage.
server is created via npm init.
react is created via npm create-react-app.
as of now this is my sample code.
server
const express = require("express");
const cors = require("cors");
const session = require('express-session');
const app = express();
require('dotenv').config();
const PORT = process.env.PORT;
app.use(express.json());
app.use(cors({
origin: 'https://app.myDomain.online',
methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
credentials: true
}));
const oneDay = 1000 * 60 * 60 * 24;
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true, sameSite: 'none' }
}));
app.get('/createSession', (req, res) => {
req.session.user = 'user';
res.send('new session is created');
});
app.get('/', (req, res) => {
res.send('get sess')
});
app.get('/getSession', (req, res) => {
if(req.session.user){
res.send('active');
}else{
res.send('not active');
}
});
app.listen(PORT, () => {
console.log(`The server is running on port ${PORT}`);
});
react
import React from 'react'
import { useEffect } from 'react';
import Axios from 'axios';
function Test() {
useEffect(() => {
Axios.get(' https://api.myDomain.online/createSession',
{ withCredentials: true }
);
}, []);
return (
<div>Test</div>
)
}
export default Test;
From the documentation for express-session...
cookie.expires
Specifies the Date object to be the value for the Expires Set-Cookie attribute. By default, no expiration is set, and most clients will consider this a “non-persistent cookie” and will delete it on a condition like exiting a web browser application.
The docs go on to prefer the maxAge property to control this. Choose a time frame that makes sense for your application. For example, 1 week...
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: { secure: true, sameSite: "none", maxAge: 7 * 24 * 60 * 60 * 1000 },
})
);
I have already fixed it a few days ago, I found out that the reason why the cookie was blocked was that the cookie has exactly the same domain as the server or probably has the same link address. As the domain of the server is api.myDomian.online, the cookie domain can't be api.myDomain.online. Not sure if that is the direct reason, but somewhat similar I think as the code works by setting a new domain to the cookie. I just removed the subdomain of the cookie like .myDomain.online and it works. here is my configuration. My backend is already deployed at aws when I test it but it could also work in render. I will try it out later on.
This is my new configuration
const oneDay = 1000 * 60 * 60 * 24;
const APP_SESSION = session({
secret: 'secrete',
resave: false,
saveUninitialized: true,
name: 'session',
cookie: {
secure: true,
sameSite: 'none'
maxAge: oneDay,
domain: '.domain.com'
}
});
Haven't tried to remove sameSite if it will still work.

How to handle express session cookies on the client side?

I'm trying to create an API with express that I will access using a React front end. I'm having a hard time figuring out how to handle authentication using express-session.
I used the middleware like follows:
var corsOptions = {
credentials: true,
origin: 'http://localhost:3000'
}
app.use(cors(corsOptions));
app.use(session({
secret: 'dfgdfbgbdfgd',
saveUninitialized: false,
resave: false,
cookie: {
secure: false
}
}));
Here is the Log in route (the local_auth middleware is just checking if the credentials are correct):
AccountRouter.post('/login', local_auth, (req, res) => {
req.session.user_id = req.user._id;
return res.status(200).send('Connected');
});
After loging in, I try to access the following route from React to check if the session is operational:
AccountRouter.get('/authcheck', (req, res) => {
let sess = req.session.user_id;
console.log(sess);
if (sess) return res.status(200);
else return res.status(404).send('pffff');
});
req.session is undefined.
The front end code is just a simple axios request to the above url. I have no idea if I have to save the cookie to localStorage and send each for each request.
Here is the request to the authcheck route:
axios.get('http://localhost:5000/api/accounts/authcheck', {withCredentials: true})
.then((response) => {
console.log(response);
})
.catch(() => {
console.log('waaah va te connecter');
});
And the login request:
const data = {
'email': e.target.email.value,
'password': e.target.password.value
};
axios.post('http://localhost:5000/api/accounts/login', data)
.then((response) => {
const sessionID = response.data;
console.log(sessionID);
});
req.session is undefined.
If req.session is undefined, then you are apparently trying to use the session in a route that is defined BEFORE this middleware code:
app.use(session({
secret: 'dfgdfbgbdfgd',
saveUninitialized: false,
resave: false,
cookie: {
secure: false
}
}));
has had a chance to run. When req.session is undefined, that means the session code has not yet run. Even if you had a cookie issue that causes a prior session to get lost, you would still have a new empty req.session if the session middleware had already run.
So, since you don't show the overall order of all your routes, we can't offer a specific fix, but it appears that this:
AccountRouter.get('/authcheck, ...)
is running before your session middleware which is a problem for any route that depends upon the session.

Cookies are not being set in production

I deployed an express server to heroku as well as a next.js app.
The cookies are being sent from the server and even being shown in the network tab:
However, the cookies are not actually stored, all my requests failed because they depends on the csrf cookie, and the storage tab is empty:
This is the code for setting the cookies in the backend:
const csrfProtection = csrf({
cookie: {
httpOnly: true,
sameSite: 'none',
secure: true,
},
});
app.set('trust proxy', 1);
app.use(cors({ credentials: true, origin: clientOrigin }));
app.get('/', csrfProtection, function (req: Request, res: Response) {
res.cookie('XSRF-TOKEN', req.csrfToken(), { sameSite: 'none', secure: true });
res.end();
});
app.use(csrfProtection);
this is my axios instance:
const baseURL = process.env.baseURL;
const axiosInstance = Axios.create({
baseURL,
withCredentials: true,
});
and the request code:
useEffect(() => {
dispatch(loadingAction.setToTrue());
const getCsrf = async () => {
await axiosInstance.get('/');
};
getCsrf()
.then(() => {
dispatch(loadingAction.setToFalse());
})
.catch((err) => {
dispatch(loadingAction.setToFalse());
setError(err);
});
}, []);
While looking at your screenshot - I observed that the browser has a different domain set hilife01 vs hilife-1
Accessing throuugh https://hlife01.herokuapp.com/auth/login - gets you the cookies but your App doesn't have the right route configured.
Most likely, The Right domain is not associated with the cookie being set so while setting the cookie, the browser silently rejects the cookie because you are not matching the domain, however it is visible in the address bar.

Passport.js cookie not persist so login auth doesn't work even though session has the passport

I'm using the passport.js local strategy.
I was testing it under proxy setting, localhost.
Things worked fine until I prepare to deploy.
I changed the API address to include dotenv and set CORS settings on the server-side.
When trying to login, CORS works fine, OPTIONS and the POST get 200 ok. The client receives the success data. cookie saved in client.
But when auth checking process runs right after Redux "isLoggedin" state is updated(useEffect), req.session doesn't
t have the passport object. So deserializeUser not be called. The session contains other cookie info except for Passport.
This one is only on Firefox(not Chrome): Page will be redirected if the login auth succeeded(it checks right after login redux state changed), but since it's failed, the user stays on the login page still. But if I try to login on the same page again, the cookie start to show the passport object.(in other words, it shows from 2nd attempt). But it doesn't persist because the Redux login state has been changed to true at the first login attempt already.(so Auth checking doesn't occur.)
client:
Axios.post(
`${process.env.REACT_APP_API_URI}/api/users/login`,
loginData,
{ withCredentials: true, }
).then((res) => res.data){
//save isLoggedin to true in Redux
}
// auth check logic starts right after changing isLoggedin. Axios Get to authenticateCheck
server.js
app.use(helmet());
// app.use(express.static('public'));
app.use("/uploads", express.static("uploads"));
// Passport configuration.
require("./utils/passport");
// connect to mongoDB
mongoose
.connect(db.mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => console.log("mongoDB is connected."))
.catch((err) => console.log(err));
// CORS Middleware
const corsOptions = {
origin: "http://localhost:8000",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
credentials: true,
methods: ["POST", "GET", "DELETE", "PUT", "PATCH", "OPTIONS"],
allowedHeaders:
"Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept, x-access-token",
};
// app.use(cors(corsOptions));
app.options(/\.*/, cors(corsOptions), function (req, res) {
return res.sendStatus(200);
});
app.all("*", cors(corsOptions), function (req, res, next) {
next();
});
// to get json data
// support parsing of application/json type post data
app.use(express.json());
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
//support parsing of application/x-www-form-urlencoded post data
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// db session store
const sessionStore = new MongoStore({
mongoUrl: db.mongoURI,
collection: "sessions",
});
// tell app to use cookie
app.use(
session({
secret: process.env.SESSION_SECRET_KEY,
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {
httpOnly: true,
secure: false,
sameSite:"none",
maxAge: 24 * 60 * 60 * 1000, // 24 hours
//keys: [process.env.COOKIE_ENCRYPTION_KEY]
},
name: "pm-user",
})
);
// tell passport to make use of cookies to handle authentication
app.use(passport.initialize());
app.use(passport.session());
app.use(compression());
app.use(flash());
app.use((req, res, next) => {
console.log("req.session:", req.session);
// console.log('/////// req: ///////', req);
console.log("////// req.user: ", req.user, " //////");
next();
});
//---------------- END OF MIDDLEWARE ---------------------//
authController:
exports.authenticateCheck = (req, res, next) => {
console.log("req.isAuthenticated():", req.isAuthenticated());
if (req.isAuthenticated()) {
return next();
} else {
return res.json({
isAuth: false,
error: true,
});
}
};
It would be a really big help if you can advise me where to look to fix it.
Thanks.
I found the solution finally.
It was because the session was renewed every time when a new request starts other than a login request.
The solution was, I had to add { withCredentials: true } to every Axios option in my frontend.

How to work with Express-session Cookies for authentication with front-end and back-end separated

I'm trying to figure out how sessions work for authentication purposes. I have an express server running on port 5000 with redis middleware creating the cookie on every response to the backend server. I also have a React app running on port 3000 to handle the front-end. The issue is that if someone goes to "localhost:3000", the cookie won't be created because they need to go to "localhost:5000" in order for a cookie to be created.
The only solution I can think of is to use useEffect() to make a request to the server to get the cookie every time. I'm not sure if this is the proper way to do it.
Server.ts:
import express from "express";
import redis from "redis";
import session from "express-session";
import connectRedis from "connect-redis";
import cors from "cors";
declare module "express-session" {
interface Session {
username: string;
password: string;
email: string;
}
}
const RedisStore = connectRedis(session);
const redisClient = redis.createClient();
redisClient.on("error", function (err) {
console.log("Could not establish a connection with redis. " + err);
});
redisClient.on("connect", function () {
console.log("Connected to redis successfully");
});
const app = express();
const corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
name: "joshcookie",
store: new RedisStore({ client: redisClient, disableTouch: true }),
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: false, secure: false },
secret: "jklbflasjlkdbhfoub4ou",
saveUninitialized: true,
resave: false,
})
);
app.get("/", (req: express.Request, res: express.Response) => {
const session = req.session;
console.log(req.session.id);
if (session.username) {
res.send("user logged in");
} else {
res.send("user not logged in");
}
});
app.post("/register", (req, res) => {
console.log(req.body);
req.session.username = req.body.username;
res.end();
});
app.listen(5000, () => {
console.log("server listening on port 5000");
});
That's exactly what webpack devServer's proxy is for. If you're using webpack in your React application add to the webpack config something like:
devServer: {
proxy: {
'/api': 'http://localhost:5000',
},
},
And while in development all your requests to localhost:3000 will go out with cookies headers and will be redirected to your local node server under the hood.
Parcel has development proxy server as well since the version 2.0.

Resources