Reputation: 105
I am able to log in and out with POSTMAN through the heroku hosted node API. In my react application, the API call with AXIOS (withcredentials:true) does not set the passport cookies, causing the session to not persist. Localhost react and Localhost server does not have this problem.
HEROKU SERVER SIDE, I have the following code:
app.use(cors({
origin: "http://localhost:3000",
credentials: true
}));
app.enable('trust proxy');
mongoose.connect(dbconfig.url, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false });
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded({extended: true}));
app.use(cookieParser('street'));
app.use(session({
secret: 'katsura street',
resave: true,
saveUninitialized: true,
proxy: true,
store: new MongoStore({ mongooseConnection: mongoose.connection },)
}));
app.use(passport.initialize());
app.use(passport.session());
I have checked that the cookie parser is above the session, the session is initialized before passport.
Is my cors affecting my local reactapp? instead of localhost, am I supposed to reference my local computer's external API?
REACT SIDE:
Axios.post(Config.ServerURL + 'auth/login',
{email: this.state.email, password: this.state.password},
{
withCredentials: true
}).then(result => {
console.log(result.data);
}).catch(error => {
//make sure message doesn't crash
if (error.response !== undefined) {
try {
console.log(error.response);
this.setState({message: error.response.data.info.message})
}catch(error) {
console.log(error);
}
}
});
Upvotes: 0
Views: 943
Reputation: 1
In my case, it was just setting, in the session settings, cookie.sameSite
to "none"
, and proxy
to true
.
Upvotes: 0
Reputation: 105
After checking the headers and seeing that the cookies are sent but filtered out, I came to a article: heroku blog
After 2019, Chrome and other browsers have cross domain cookies disabled to prevent CSRF attacks.
In my use case, I can just turn it off with the following on the Node API server:
app.use(session({
secret: 'street',
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
sameSite:'none',
secure:true
},
store: new MongoStore({ mongooseConnection: mongoose.connection },)
}));
changing samesite to none, will allow chrome to set your cookies with cross domains.
Upvotes: 1