Search code examples
androidnode.jscsrf

with node.js server built in CSRF protection, how do the mobile apps receives the CSRF token?


I am using the node.js and express to build a simple server, in which CSRF is being imlemented through express framework.

app.use(express.csrf()); 
app.use(function(req, res, next){
  res.locals.token = req.session._csrf;
  res.locals.year = new Date().getFullYear();
  next();
});

The Connect CSRF middleware automatically generates the req.session._csrf token, and this function maps it to res.locals.token so it will be available to templates made from ejs. This works well with web application.

But when it comes to my mobile application made from android, for example to login, only send the username and password without the CSRF token will lead the server to reject the request.

as the previous code works only for web template, so my question is how to receive this token in the android enabled application

best rgds xi


Solution

  • If it was only the login page you need to protect, then you could easily do a GET for the Login page first (which returns JSON or XML) and pick up the CSRF token that way.

    However, I think CSRF isn't an issue for mobile devices. What you could do instead is use the cookiesession middleware to set a flag on the session to indicate that this type of client doesn't require CSRF.

    Then use this answer Disable csrf validation for some requests on Express to turn CSRF on or off depending on whether that flag is present in the cookie.

    Alternatively, your mobile app could just add a flag to every request url instead of using the cookie approach indicate that it doesn't require CSRF. However, that means a hacker could just bypass your CSRF protection if they know this flag.