BadRequestError: checks.state argument is missing - What changed? - node.js

Tabled a development project back in November and picked it back up.
The authorization that was working is not working any longer and gives me the following error.
BadRequestError: checks.state argument is missing
at /base/node_modules/express-openid-connect/middleware/auth.js:121:31
at processTicksAndRejections (internal/process/task_queues.js:95:5)
Originally I was running my server in development over http, but I thought maybe the issue was that my local server was not HTTP, so now I'm accessing it over HTTPs with a self signed certificate, if perhaps that is the issue.
I am using an ngrok proxy to support the callback to my development environment and have
OIDC_RP_URI=https://myproxy.ngrok.io
OIDC_COOKIE_DOMAIN=myproxy.ngrok.io
auth = {
authRequired: true, // validate<boolean>('DISABLE_SSO', Boolean(env.DISABLE_SSO), isBoolean, false),
baseURL: validate<string>('OIDC_RP_URI', env.OIDC_RP_URI, isString),
clientID: validate<string>('OIDC_CLIENT_ID', env.OIDC_CLIENT_ID, isString),
issuerBaseURL: validate<string>('OIDC_OP_URI', env.OIDC_OP_URI, isString),
routes: {
callback: validate<string>('OIDC_REDIRECT_PATH', env.OIDC_REDIRECT_PATH, isString),
logout: '/logout',
postLogoutRedirect: 'https://xx/Logout'
},
secret: validate<string>('EXPRESS_SESSION_SECRET', env.EXPRESS_SESSION_SECRET, isString),
session: {
cookie: {
domain: validate<string>('OIDC_COOKIE_DOMAIN', env.OIDC_COOKIE_DOMAIN, isString),
httpOnly: true,
path: '/',
sameSite: 'None' as const, // 'Lax' as const,
secure: true
},
absoluteDuration: 60 * 60 * 8,
rollingDuration: 60 * 60
}

Related

Not being able to remove cookies on nextjs in production

I am creating an application in NextJs and I set the cookie authorization when the user make login:
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", `Bearer ${jwtGenerated}`, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 60 * 60 * 12,
path: "/",
})
]);
This part of the code works perfectly, it sets the cookie in the browser. However when I log out, I make a request to the url /api/logout that executes this code:
import cookie from "cookie";
export default (req, res) => {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
};
however it seems that it does not work in production. When I'm at localhost it removes cookies and changes their value. However in production nothing is changed. The expiration remains the same, value and everything else.
Am I doing something wrong? Is there any other way to remove this cookie when the user make logout?
Are you using Vercel as the deployment platform? This bug is caused because Next.js's serverless features always return a 304 Not Modified. Quite frankly I don't know why this happens on the server, but I believe that it has something to do with HTTP requests on Next.js's internals.
In order to fix this problem, I made the logout request a POST request with a static key. This will prevent 304 Not Modified error from happening.
import cookie from "cookie";
export default (req, res) => {
if (req.method !== 'POST') return res.status(405).json({ status: 'fail', message: 'Method not allowed here!' });
if (req.body.key === 'static_key') {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
}
return res.status(400).json({ status: 'fail', message: 'Bad request happened!' });
};

Set user info with cookie-session

I'm using cookie-session to store all my session information.
After my users login, I store his information inside req.session.user like this
req.session.user = _.omit(client.dataValues, [
"password",
"createdAt",
"updatedAt"
]);
Using console.log I can see that everything is setted ok, but when I try to use req.session.user in another route, I get undefined.
My cookie is setted like this
app.use(
cookiesession({
name: "name",
keys: ["key1", "key2"],
maxAge: 24 * 60 * 60 * 1000,
httpOnly: false,
options: {
secure: false,
secret: "secrete",
overwrite: true
}
})
);

sails.js session data not saved into db

I might be doing something wrong. Please guide me in right direction.
I am trying to implement sails session feature with 'connect-mongo'. I did the implementation same as explained in the docs Sails session mongo. After successful authentication I am trying to save session data into mongoDb. But in my case it is not saved in mongo collection and collection always remains empty.
My configurations in session.js
url: 'mongodb+srv://username:password#cluster0-tkjwp.mongodb.net/mydbname?retryWrites=true',
collection: 'sessions',
auto_reconnect: false,
ssl: false,
stringify: true,
cookie: {
secure: false,
maxAge: 24 * 60 * 60 * 1000
}
and how I am trying to save.
if(user.length && user[0].id){
// save in DB
req.session.authenticated = true;
req.session.authinfo = user[0];
req.session.save(function(err) {
console.log(req.session);
return res.json({
status: 1,
msg: 'Successfull.'
});
})
}else{
return res.send({
status: 0,
msg: 'Invalid'
});
}
Also I am not getting any error
Its working now. Only thing I missed the adapter option. But now I am using it with mysql. Below I posting my working code with MySql.
In session.js
adapter: 'express-mysql-session',
host: 'localhost',
port: 3306,
user: 'root',
password: 'xxxxxxxxx',
database: 'xyz',
ssl: false,
stringify: true,
cookie: {
maxAge: 24 * 60 * 60 * 1000
},

If no express-cookie timeout is set, is there a defaulted timeout as a preset?

With express session, if you do not specify a max timeout example:
cookie: { maxAge: new Date(Date.now() + (60 * 1000 * 30)) })
is there a default time that is preset?
It's right there in the docs, man:
"Settings object for the session ID cookie. The default value is { path: '/', httpOnly: true, secure: false, maxAge: null }."

Accessing Loopback config data from middleware

Say we are in Loopback middleware, such as
app.use(function(req,res,next){
// I am not sure what key to use here in the getter...
const config = app.get('?');
});
I want to access the overall config that Loopback is using.
I tried:
const config = app.get('config');
const config = app.get('env');
const config = app.get('datasources');
nothing gives me quite what I want.
Interestingly, this gives me:
console.log(app.get('restApiRoot'));
=> '/api'
so that's a clue to what's going on, but I want to get the parent object(s) for the above data.
how can we access the configuration that Loopback has loaded. The configuration of course varies by environment variables etc.
I want to log what datasources.x.js file was loaded and what config.x.js file was loaded, and any other server configuration info I can capture.
Having a lot of trouble figuring out how to do this.
This seems to be the same question I have:
https://github.com/strongloop/loopback/issues/1526
but they point me to the void that is Google Groups and I searched through there and couldn't find what the answer to this question.
This behavior is actually inherited from Express.
The entire config is stored in the app.settings object, with app.get(key) and app.set(key,value) just acting as getter/setter.
Doing console.log(app.settings); (in server/server.js for instance) it on a fresh loopback install returns the following:
{ 'x-powered-by': true,
etag: 'weak',
'etag fn': [Function: wetag],
env: 'development',
'query parser': 'extended',
'query parser fn': [Function: parseExtendedQueryString],
'subdomain offset': 2,
'trust proxy': false,
'trust proxy fn': [Function: trustNone],
view: [Function: View],
views: 'C:\\Users\\*******\\Documents\\GitHub\\lbtest\\views',
'jsonp callback name': 'callback',
host: '0.0.0.0',
port: 3000,
restApiRoot: '/api',
remoting:
{ context: { enableHttpContext: false },
rest: { normalizeHttpPath: false, xml: false },
json: { strict: false, limit: '100kb' },
urlencoded: { extended: true, limit: '100kb' },
cors: false,
errorHandler: { disableStackTrace: false } },
legacyExplorer: false,
'loopback-component-explorer': { mountPath: '/explorer' },
url: 'http://localhost:3000/' }

Resources