prism

2013-08-21

expressjs conditional CSRF

現在一般基本的網路服務,為了安全性,會加上 CSRF 的保護,如果

用 ajax 的方式傳資料,一般可以跳過,或是,加在 ajax 的 header 裏面


在 Django 下面的話,如果不檢查的話,會加個 decorator @csrf_exempt

在 expressjs 下面,加 ajax header 是可行的,不過懶一點,目前 API 路徑的
請求,先跳過,以下筆記



 /**
 * Module dependencies.
 */

var express = require('express')
  , csrf = express.csrf()
  , fs = require('fs')
  , mongoStore = require('connect-mongo')(express)
  , flash = require('connect-flash')
  , helpers = require('view-helpers')
  , mongoose = require('mongoose')
  , http = require('http')
  , path = require('path')
  , i18n = require('i18n');


  // I olny cut the block of csrf setup

  // adds CSRF support
  if (process.env.NODE_ENV !== 'test') {

    // conditinal CSRF
    
    var conditionalCSRF = function(req, res, next){
      
      // bypass urlpath start with api and moreurl

      if (! /^\/(api|moreurl)/.test(req.path)){
        csrf(req, res, next);
      } else {
        next();
      }
    }
    //app.use(express.csrf());
    app.use(conditionalCSRF);
  }

  // This could be moved to view-helpers :-)
  app.use(function(req, res, next){
    res.locals.csrf_token = req.session._csrf
    next()
  })


參考
http://stackoverflow.com/questions/13516898/disable-csrf-validation-for-some-requests-on-express

http://stackoverflow.com/questions/11200068/how-to-implement-csrf-protection-in-ajax-calls-using-express-js-looking-for-com

沒有留言: