Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove csrf protecteion on API post calls

I would like to remove csrf from my Express 3.0 application as i don't need it there. I use oauth to validate clients. Is the a middleware to whitelist API urls when using express.csrf()?

like image 229
samaras Avatar asked Mar 10 '14 08:03

samaras


People also ask

How do you prevent CSRF attacks in REST API?

If our project requires CSRF protection, we can send the CSRF token with a cookie by using CookieCsrfTokenRepository in a custom WebSecurityConfigurerAdapter. After restarting the app, our requests receive HTTP errors, which means that CSRF protection is enabled.

Can we turn off CSRF protection?

To disable CSRF protection on all routes. So navigate to app\Http\Middleware and open VerifyCsrfToken. php file. Then update the routes, which you want to disable CSRF protection.

Does CSRF work with POST requests?

A CSRF attack can either leverage a GET request or a POST request (though a POST request is more complicated and is thus uncommon). Either one needs to start with an attacker tricking a victim into loading or submitting the information to a web application.

Is CSRF protection needed for REST API?

Enabling cross-site request forgery (CSRF) protection is recommended when using REST APIs with cookies for authentication. If your REST API uses the WCToken or WCTrustedToken tokens for authentication, then additional CSRF protection is not required.


1 Answers

You can do that in two ways.

1.) Create a small middleware of your own to allow white list url patterns not to be blocked by csrf like;

var express = require("express");
var expressCsrf = express.csrf();
var app = express.createServer();

var customCsrf = function (req, res, next) {
    // I assume exact match, but you can use regex match here
  var csrfEnabled = true;
  var whiteList = new Array("/pattern1/param1","/pattern2/param2","/pattern3/param3");
  if (whiteList.indexOf(req.path) != -1) {
    csrfEnabled = false;
  }

  if (csrfEnabled) {
    expressCsrf(req, res, next);
  } else {
    next();
  }
}

app.use(customCsrf);
app.listen(3000);

2.) Use csrf middleware on your controllers you want to enable. For example, you want to use csrf check on profile save controller;

app.post("/profile/save", express.csrf(), function(req, res, next) {
    // put your code here
});
like image 60
Hüseyin BABAL Avatar answered Oct 07 '22 01:10

Hüseyin BABAL