Home » Articles

How to protect Server from CSRF Attacks?

In this example, we are going to learn about how to protect your server from CSRF attacks?
By: Manu Jemini, on 24 JAN 2018

Prerequisite: Cross-Site Request Forgery (CSRF) Attacks

It is an abbreviation of Cross-Site Request Forgery, which means that an attacker can make you do some unwanted actions to exploit the user and the server itself.

CSFR Attacks - How to protect server?

Image source: https://adriancitu.files.wordpress.com/2017/12/csrfserver.png

To protect your server from attackers use a simple npm package called csurf. To add it in your project use the npm command : npm install csurf.

Let us see a quick example about how to use it?

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
 
// setup route middlewares 
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
 
// create express app 
var app = express()
 
// parse cookies 
// we need this because "cookie" is true in csrfProtection 
app.use(cookieParser())
 
app.get('/form', csrfProtection, function(req, res) {
  // pass the csrfToken to the view 
  res.render('send', { csrfToken: req.csrfToken() })
})
 
app.post('/process', parseForm, csrfProtection, function(req, res) {
  res.send('data is being processed')
})

Now as you can see we are injecting a security token into the view from the get function. This means our view knows about it and whenever it will make a request back to the server, we can check and validate it.

<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  
  Favorite color: <input type="text" name="favoriteColor">
  <button type="submit">Submit</button>
</form>

This is fairly a decent approach. Easy and simple. But what if the request is coming from outside of your website, this will make the situation a bit different as we cannot inject the token everywhere. To tackle this situation just disables the security.

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
var app = express()
 
var api = createApiRouter()
 app.use('/api', api)
 
// now add csrf and other middlewares, after the "/api" was mounted 
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
 
app.get('/form', function(req, res) {
  // pass the csrfToken to the view 
  res.render('send', { csrfToken: req.csrfToken() })
})
 
app.post('/process', function(req, res) {
  res.send('csrf was required to get here')
})
 
function createApiRouter() {
  var router = new express.Router()
 
  router.post('/getProfile', function(req, res) {
    res.send('no csrf to get here')
  })
 
  return router
}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.