Skip to content

Commit a16482c

Browse files
committed
CORS security ulnerability fixed with a secure origin validation function
1 parent 22494f1 commit a16482c

1 file changed

Lines changed: 33 additions & 7 deletions

File tree

server/app.js

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,40 @@ var cors = require("cors");
1515

1616
const app = express();
1717

18+
const allowedOrigins = [
19+
'http://localhost:3000',
20+
'http://localhost:3001',
21+
process.env.NEXTAUTH_URL,
22+
process.env.FRONTEND_URL,
23+
].filter(Boolean); // Remove undefined values
24+
25+
// CORS configuration with origin validation
26+
const corsOptions = {
27+
origin: function (origin, callback) {
28+
29+
if (!origin) return callback(null, true);
30+
31+
32+
if (allowedOrigins.includes(origin)) {
33+
return callback(null, true);
34+
}
35+
36+
37+
if (process.env.NODE_ENV === 'development' && origin.startsWith('http://localhost:')) {
38+
return callback(null, true);
39+
}
40+
41+
// Reject other origins
42+
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
43+
return callback(new Error(msg), false);
44+
},
45+
methods: ["GET", "POST", "PUT", "DELETE"],
46+
allowedHeaders: ["Content-Type", "Authorization"],
47+
credentials: true, // Allow cookies and authorization headers
48+
};
49+
1850
app.use(express.json());
19-
app.use(
20-
cors({
21-
origin: "*",
22-
methods: ["GET", "POST", "PUT", "DELETE"],
23-
allowedHeaders: ["Content-Type", "Authorization"],
24-
})
25-
);
51+
app.use(cors(corsOptions));
2652
app.use(fileUpload());
2753

2854
app.use("/api/products", productsRouter);

0 commit comments

Comments
 (0)