Node.js expressjs sessions don't stick in Firefox - session

I'm using express with nodejs and sessions don't stick in Firefox. The work fine in Chrome however.
I have my maxAge to 14400000 which I've read could be an issue since my local machine is on GMT, but still it doesn't seem to stick.
This is what I have configured:
app.use(express.cookieParser());
app.use(express.session({ secret: 'mysecret', store: new RedisStore, cookie: { maxAge: 14400000 }}));
I'm setting it simply by doing:
req.session.user = 'something'
Any ideas what this could be?
Thank you!

Try using req.session. regenerate(callback) when you first establish the session. It would look something like this:
app.use(express.cookieParser());
app.use(express.session({ secret: 'mysecret', store: new RedisStore, cookie: { maxAge: 14400000 }}));
var user = //Define your user
req.session.regenerate(function() {
req.session.user = user;
res.redirect('/loggedin');
});
Give it a try!

Without wasting time here is the fix:
app.use(
session({
httpOnly: false,
secret: "top secret",
})
);
Now if you are interested in real story:
Mozilla is a strict browser. She play by the rules. If something is not working in Mozilla but in chrome its mean you are doing it wrong.
In production environment there we set https . and by default express.session httpOnly is true, just make it false.
:) so it can also work on https.

Related

Contentful ignoring proxy configuration

I'm trying to setup a proxy to Contentful Delivery SDK to intercept the response and add relevant data. For development purposes, the proxy is still running locally. This is the configuration I'm using right now:
const client = createClient({
space: SPACE_ID,
accessToken: ACCESS_TOKEN,
host: CDN_URL,
environment: ENVIRONMENT,
basePath: 'api',
retryOnError: false,
proxy: {
host: 'localhost',
port: 8080,
auth: {
username: 'username',
password: 'password',
},
},
});
For some reason, this client keeps ignoring the proxy settings, making the request directly to Contentful CDN. I tried removing the host field from the configuration, but it didn't change the outcome. I also tried using the httpsAgent configuration with HttpsProxyAgent instead of the proxy one, but also didn't work.
Versions:
"contentful": "^7.11.3"
"react": "^16.13.1"
Firstly, the proxy configuration cannot be used client-side. It's unclear if that is your use case here.
There is a known bug here. Either try installing a newer version of Axios, which is the lib that the contentful SDK uses. Or use a proxyAgent:
const HttpProxyAgent = require("http-proxy-agent");
const httpAgent = new HttpProxyAgent({host: "proxyhost", port: "proxyport", auth: "username:password"})
Now just pass the agent into the create client method:
const client = createClient({
....
httpAgent: httpAgent,
....
});

MERN app works locally but not on heroku netlify [duplicate]

Express-Session is working in development environment, as it sets the "connect.sid" cookie in my browser. However, in production it's not storing the cookie, and instead of using the same session - it creates a new one every time. I believe that the issue would be fixed if I can somehow save third party cookies, as my app was deployed using Heroku. Lastly, I have also used express-cors to avoid the CORS issue (don't know if this has anything to do with the cookie issue). I have set {credentials: true} in cors, {withCredentials: true} in Axios, as well.
Heroku uses reverse proxy. It offers https endpoints but then forwards unencrypted traffic to the website.
Try something like
app.enable('trust proxy')
And check out
https://expressjs.com/en/guide/behind-proxies.html
Issue Solved! -> Add sameSite: 'none'
Full Cookie config (express-session) for production:
cookie: {
httpOnly: true,
secure: true,
maxAge: 1000 * 60 * 60 * 48,
sameSite: 'none'
}
Adding a "name" attribute to the session config worked for me:
{
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
proxy: true, // Required for Heroku & Digital Ocean (regarding X-Forwarded-For)
name: 'MyCoolWebAppCookieName', // This needs to be unique per-host.
cookie: {
secure: true, // required for cookies to work on HTTPS
httpOnly: false,
sameSite: 'none'
}
}

NestJs Cookies when serving API into Heroku

const validateUser = await this.authService.validateUser(email, password);
const jwt = await this.authService.login(validateUser);
const cookie = response.cookie('jwt', jwt.access_token, { httpOnly: true });
Environment :
Nuxt.js host on Netlify
Nest.js host on Heroku
I'm using cookies in local development to make request after being loged.
But when I'm trying to host the front and back into Netlify and Heroku, the cookies do not be set (with the same configuration)
Is there a config needed to make it work ?
Edit :
response.cookie('jwt', jwt.access_token, {
httpOnly: true,
sameSite: 'none',
secure: true,
});
Google chrome need this configuration to make cookies working

Session cookie is not set in browser

I have frontend client running on custom Next.js server that is fetching data with apollo client.
My backend is graphql-yoga with prisma utilizing express-session.
I have problem with picking correct CORS settings for my client and backend so cookie would be properly set in the browser, especially on heroku.
Currently I am sending graphql request from client with apollo-client having option
credentials: "include" but also have tried "same-origin" with no better result.
I can see cookie client in response from my backend in Set-Cookie header, and in devTools/application/cookies. But this cookie is transparent to browser and is lost on refresh.
With this said I also tried to implement some afterware to apollo client as apolloLink that would intercept cookie from response.headers but it is empty.
So far now I'm thinking about pursuing those two paths of resolving the issue.
(I'm only implementing CORS because browser prevents fetching data without it.)
CLIENT
ApolloClient config for client-side:
const httpLink = new HttpLink({
credentials: "include",
uri: BACKEND_ENDPOINT,
});
Client CORS usage and config:
app
.prepare()
.then(() => {
const server = express()
.use(cors(corsOptions))
.options("*", cors(corsOptions))
.set("trust proxy", 1);
...here goes rest of implementation
const corsOptions = {
origin: [process.env.BACKEND_ENDPOINT, process.env.HEROKU_CORS_URL],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie", '*'],
methods: "GET,POST",
optionsSuccessStatus: 200
};
My atempt to get headers from response in apolloClient(but headers are empty and data is not fetched afterwards):
const middlewareLink = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
const context = operation.getContext();
const {response: {headers}} = context;
if (headers) {
const cookie = response.headers.get("set-cookie");
if (cookie) {
//set cookie here
}
}
return response;
});
});
BACKEND
CORS implementaion (remeber that is gql-yoga so I need first to expose express from it)
server.express
.use(cors(corsOptions))
.options("*", cors())
.set("trust proxy", 1);
...here goes rest of implementation
const corsOptions = {
origin: [process.env.CLIENT_URL_DEV, process.env.CLIENT_URL_PROD, process.env.HEROKU_CORS_URL],
credentials: true,
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie"],
exposedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "X-Forwarded-Proto", "Cookie", "Set-Cookie"],
methods: "GET,HEAD,PUT,PATCH,POST,OPTIONS",
optionsSuccessStatus: 200
};
Session settings, store is connect-redis
server.express
.use(
session({
store: store,
genid: () => uuidv4(v4options),
name: process.env.SESSION_NAME,
secret: process.env.SESSION_SECRET,
resave: true,
rolling: true,
saveUninitialized: false,
sameSite: false,
proxy: STAGE,
unset: "destroy",
cookie: {
httpOnly: true,
path: "/",
secure: STAGE,
maxAge: STAGE ? TTL_PROD : TTL_DEV
}
})
)
I am expecting session cookie to be set on the client after authentication.
Actual result:
Cookie is visible only in Set-Cookie response header but is transparent to browser and not persistent nor set (lost on refresh or page change). Funny enough I can still make authenticated requests for data.
This may not be a CORS issue, it looks like a third-party cookie problem.
Behaviour could be different across browsers so I recommend testing several ones. Firefox (as of version 77) seems to be less restrictive. In Chrome (as of version 83) there is an indicator on the far right of the URL bar when a third party cookie has been blocked. You can confirm whether third party cookies is the cause of the problem by creating an exception for the current website.
Assuming your current setup is as follows:
frontend.com
backend.herokuapp.com
Using a custom domain for your backend that is a subdomain of your frontend would solve your problem:
frontend.com
api.frontend.com
The following setup wouldn't work because herokuapp.com is included in the Mozilla Foundation’s Public Suffix List:
frontend.herokuapp.com
backend.herokuapp.com
More details on Heroku.

How do I log out of Stormpath ID Site with express-stormpath and stormpath-sdk-angularjs?

I have an express-stormpath application that uses Stormpath ID Site. It has this configuration:
app.use(stormpath.init(app, {
web: {
idSite: {
enabled: true,
uri: '/idSiteResult',
nextUri: '/'
},
login: {
enabled: true,
uri: config.login
},
logout: {
enabled: true,
uri: config.logout
},
me: {
expand: {
customData: true,
groups: true
}
}
}
}));
Login works fine, but logout is giving me trouble.
First, I tried logging out with the stormpath-sdk-angularjs built-in endSession()
$auth.endSession();
But I was still logged in.
Digging into express-stormpath, it looks like logout POST requires Accept type text/html for id-site logout. In stormpath-sdk-angularjs, it looks like endSession POST uses application/json.
So I tried logging out with $http.post
$http.post('/logout', null, {
headers: {
'Accept': 'text/html'
}
});
But I get this error:
XMLHttpRequest cannot load https://api.stormpath.com/sso/logout?jwtRequest=[...]. Redirect from 'https://api.stormpath.com/sso/logout?jwtRequest=[...]' to 'http://localhost:9000/idSiteResult?jwtResponse=[...]' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
How do I log out of Stormpath ID Site?
I work at Stormpath. ID Site requires that you actually redirect the end user to ID Site. I'm not sure why endSession() isn't working, but I'll reach out to our JS team to see if there might be a bug there.
In the meantime, you can use this code (or the equivalent in Angular-specific primitives) to accomplish a logout:
var form = document.createElement('form');
form.method = "POST";
form.action = "/logout";
form.submit();
This looks like a CORS issue. I believe you need to add at least;
Access-Control-Allow-Origin: https://api.stormpath.com
To the response headers from your server.

Resources