How to use csurf - 10 common examples

To help you get started, we’ve selected a few csurf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github im6 / vp / src / server / middlewares / csrfHandler.js View on Github external
import csrf from 'csurf';
import get from 'lodash.get';
import { CSRF_EXCEPTION } from '../config';

const csrfOrigin = csrf();
export default (...args) => {
  // args will be [req, res, next]
  const self = this;
  if (get(args[0], 'body._csrf', null) === CSRF_EXCEPTION) {
    console.log('csrf exception'); // eslint-disable-line no-console
    args[2]();
  } else {
    csrfOrigin.apply(self, args);
  }
};
github im6 / vp / server / middlewares / csrfOverride.js View on Github external
import csrf from 'csurf';
import get from 'lodash.get';
import { CSRF_EXCEPTION } from '../config';

const csrfOrigin = csrf();
const csrfOverride = (...args) => {
  // args will be [req, res, next]
  const self = this;
  if (get(args[0], 'body._csrf', null) === CSRF_EXCEPTION) {
    console.log('csrf exception'); // eslint-disable-line no-console
    args[2]();
  } else {
    csrfOrigin.apply(self, args);
  }
};

export default csrfOverride;
github localnerve / react-pwa-reference / src / application / server / index.js View on Github external
app.use(errorHandler.maintenance());

// Handle special requests
app.use(rewriteBasics(settings));
app.use(rewriteServiceWorker(settings));

// Serve cached statics
app.use(settings.web.baseDir, statics(settings));

// Setup security
app.use(cookieParser({
  httpOnly: true,
  secure: settings.web.ssl
}));
app.use(bodyParser.json());
app.use(csrf({ cookie: true }));

// Register services, handle service requests
const fetchrPlugin = fluxibleApp.getPlugin('FetchrPlugin');
fetchrPlugin.registerService(servicesRoutes);
fetchrPlugin.registerService(servicesPage);
fetchrPlugin.registerService(servicesContact);
fetchrPlugin.registerService(servicesSubscription);
fetchrPlugin.registerService(servicesPush);
app.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());

// Handle robots.txt
app.get(settings.web.robots, robots);

// Handle sitemap.xml
app.get(settings.web.sitemap, sitemap);
github gpbl / isomorphic500 / src / server.js View on Github external
// Set the default locale

  locale.Locale.default = config.locales[0];

  // Set req.locale based on the browser settings

  app.use(locale(config.locales));

  // Overwrite req.locale either from cookie or querystring

  app.use(setLocale);

  // This is used by the fetchr plugin

  app.use(csurf({ cookie: true }));

  // Configure fetchr (for doing api calls server and client-side)
  // and register its services

  const fetchr = fluxibleApp.getPlugin("FetchrPlugin");
  fetchr.registerService(require("./services/photos"));
  fetchr.registerService(require("./services/photo"));

  // Use the fetchr middleware (will enable requests from /api)

  app.use(fetchr.getXhrPath(), fetchr.getMiddleware());

  // Use the `static` dir for serving static assets. On production, it contains the js
  // files built with webpack
  app.use(serveStatic(staticPath, {
    maxAge: 365 * 24 * 60 * 60
github LukeLin / react-ocean / server / app.js View on Github external
maxAge: 86400000
}));

// if(process.env.NODE_ENV !== 'production'){
//     let webpack = require('webpack');
//     let config = require('../create-webpack.config')(true);
//     let webpackDevMiddleware = require('webpack-dev-middleware');
//     let webpackHotMiddleware = require('webpack-hot-middleware');
//     let compiler = webpack(config);
//     app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
//     app.use(webpackHotMiddleware(compiler));
// }

app.use(allowCrossDomain);

app.use(csurf());
app.use(function (req, res, next) {
    res.locals.csrftoken = req.csrfToken();
    next();
});
app.use(reactRender({
    transformer: function(data){
        return Immutable.fromJS(data);
    }
}));

app.use('/api', apis);
app.use('/', routes);
app.use('*', spaRenderMatch);

// error handlers
// no stacktraces leaked to user
github PacktPublishing / Securing-Applications-in-Node.js-V- / demo-project / src / server.js View on Github external
app.use(csrfProtection());

app.use(express.static(__dirname + '/public'));

app.use(
  cookieSession({
    name: 'session',
    maxAge: '30 days',
  }),
);

app.use(urlencoded({extended: false}));
app.use(json());

app.use(csurf());

app.use(Routes);

app.use(express.static(__dirname + '/../public'));

const PORT = process.env.PORT || 3000;
app.listen(PORT);
console.log(`Listening on http://localhost:${PORT}`);
github Madmous / madClones / server / users-microservice / src / app.js View on Github external
app.use(helmet());

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(cookieParser());

app.disable('x-powered-by');

app.use(`${rootUrl}signcheck`, signCheckRoutes);
app.use(`${rootUrl}signout`, signOutRoutes);
app.use(`${rootUrl}signup`, signUpRoutes);
app.use(`${rootUrl}signin`, signInRoutes);

app.use(csurf({ cookie: true }));

app.use((err, req, res, next) => {
  if (err instanceof expressValidation.ValidationError) {
    const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and ');

    return res.status(err.status).json({
      message: unifiedErrorMessage
    });
  }
});

app.use((req, res) => {
	res.status(404).json({
		status: 404,
		message: 'The requested URL ' + req.originalUrl + ' was not found on the server.'
	});
github Madmous / madClones / server / trello-microservice / src / app.js View on Github external
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(cookieParser());

app.disable("x-powered-by");

app.use(`${rootUrl}signin`, authenticatedWithBasic, signInRoutes);
app.use(`${rootUrl}signup`, signUpRoutes);

app.use(`${rootUrl}organizations`, authenticatedWithToken, organizationRoutes);
app.use(`${rootUrl}boards`, authenticatedWithToken, boardRoutes);
app.use(`${rootUrl}users`, authenticatedWithToken, userRoutes);
app.use(`${rootUrl}home`, authenticatedWithToken, homeRoutes);

app.use(csurf({ cookie: true }));

app.use((err, req, res, next) => {
  if (err instanceof expressValidation.ValidationError) {
    const unifiedErrorMessage = err.errors
      .map(error => error.messages.join(". "))
      .join(" and ");

    return res.status(err.status).json({
      message: unifiedErrorMessage
    });
  }
});

app.use((req, res) => {
  res.status(404).json({
    status: 404,
github recruit-tech / redux-pluto / src / server / index.ts View on Github external
export default function renderer({
  clientStats,
  server,
  sessionStore,
  promises,
}: any) {
  const app = express.Router();

  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded(config.bodyParser.urlencoded));
  app.use(cookieParser(config.cookieParser as any));
  app.use(session({ store: sessionStore, ...config.session }));
  app.use(csurf(config.csurf));
  app.use(serverTiming());
  app.use(favicon(config.favicon));
  app.use(useragent.express());

  if (!__DEVELOPMENT__) {
    const assetsHandler = new AssetsHandler(clientStats.assets);
    app.use(
      clientStats.publicPath,
      assetsHandler.handleUrl.bind(assetsHandler),
    );
  }

  config.assets.forEach(asset => {
    app.use(asset.mount, express.static(asset.path));
  });
github alphagov / paas-admin / src / components / app / app.ts View on Github external
secure: !config.allowInsecureSession,
    httpOnly: true,
  }));

  app.use('/assets', staticGzip('dist/assets', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/govuk-frontend/govuk', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/govuk-frontend/govuk/assets', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/d3/dist', {immutable: true}));
  app.use('/assets', staticGzip('node_modules/d3-sankey/dist', {immutable: true}));
  app.use(compression());

  app.use(helmet());
  app.use(helmet.contentSecurityPolicy(csp));

  app.use(express.urlencoded({extended: true}));
  app.use(csrf());

  app.get('/healthcheck', (_req: express.Request, res: express.Response) => res.send({message: 'OK'}));

  app.get('/forbidden', () => {
    throw new NotAuthorisedError('Forbidden');
  });

  app.get('/calculator', (req: express.Request, res: express.Response, next: express.NextFunction) => {
    const route = router.findByName('admin.home');
    const ctx = initContext(req, router, route, config);

    getCalculator(ctx, {...req.query, ...req.params, ...route.parser.match(req.path)})
      .then((response: IResponse) => {
        res.status(response.status || 200).send(response.body);
      })
      .catch(err => internalServerErrorMiddleware(err, req, res, next));

csurf

CSRF token middleware

MIT
Latest version published 4 years ago

Package Health Score

58 / 100
Full package analysis

Popular csurf functions