Answer the question
In order to leave comments, you need to log in
How to organize csrf protection for NodeJS API?
There are 3 NodeJS applications on the server: public(angular + nodejs for uploading files), admin(same as public), API(nodejs). Nginx is configured as a reverse proxy so the config looks like this:
server {
listen 80 default_server;
listen[::]: 80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
server {
listen 443;
server_name example.com;
ssl on;
ssl_certificate / home / example.com / ssl - bundle.crt;
ssl_certificate_key / home / example.com / private - key.key;
ssl_prefer_server_ciphers on;
root /var/www/html;
index index.html index.htm index.nginx - debian.html;
location / {
proxy_pass http://localhost:4444;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location / api {
proxy_pass http://localhost:5555;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location / admin {
proxy_pass http://localhost:7777;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
const csurf = require('csurf');
const csrfProtection = csurf({
cookie: true
});
app.use(cookieParser());
if (process.env.PROD) {
app.use(csrfProtection);
}
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:7777"); // порт ангуляра
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, XSRF-TOKEN");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE');
res.header("Access-Control-Allow-Credentials", "true");
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question