Skip to content

Clarification of the recommended method to share csrf tokens with the client #124

@slidenerd

Description

@slidenerd
Image
  • Your documentation says dont send the CSRF token as JSON, what does that mean?

const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({
	cookieName: "_csrf",
	getSecret: () => "",
	getSessionIdentifier: (req) => {
		// Use a combination of IP and User-Agent as session identifier
		return `${req.ip || ""}-${req.get("user-agent") || ""}`;
	},
	ignoredMethods: ["HEAD", "OPTIONS"],
});

const app = express();

app.use(httpLogger);
app.use(helmet());
app.use(cors(corsOptions));
app.all("/api/auth/*", toNodeHandler(auth));
app.use(cookieParser());
app.use(express.json({ limit: "1MB" }));
app.use(express.urlencoded({ extended: true, limit: "1MB" }));
app.get("/", (_req: Request, res: Response, _next: NextFunction) => {
	return res.json({ message: "Hello World" });
});
// IS THIS A BAD IDEA?
app.get("/csrf-token", (req: Request, res: Response) => {
	const token = generateCsrfToken(req, res);
	return res.json({ token });
});
app.get(
	"/encryption/test",
	doubleCsrfProtection,
	(_req: Request, res: Response) => {
		const data = [
			{ id: 1, name: "something" },
			{ id: 2, name: "anything" },
			{ id: 3, name: "nothing" },
		];
		return res.json(data);
	},
);
app.use(notFoundHandler);
app.use(defaultErrorHandler);

export { app };

  • Is adding the /csrf-token endpoint above a bad idea?
  • If csrf tokens are set on http only cookies, that means the clients wont be able to read them
  • Just to clarify, my client is a sveltekit application running on 5173 while express runs on 3002 above and cors origins have been added to make this work
  • how do you communicate the tokens if the above statement about JSON is true?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions