https://gitissue.com/repos/jiayisheji/blog

pass csrf https://github.com/expressjs/csurf/issues/21

main.ts

  
import { NestFactory } from '@nestjs/core';  
import { NestExpressApplication } from '@nestjs/platform-express';  
import { join } from 'path'  
import { AppModule } from './app.module';  
import * as cookieSession from 'cookie-session';  
import * as helmet from 'helmet';  
import * as cookieParser from 'cookie-parser';  
import * as csurf from 'csurf';  
import * as rateLimit from 'express-rate-limit';  
  
async function bootstrap() {  
  const app = await NestFactory.create(  
    AppModule,  
  );  
  
  app.init()  
    
  app.useStaticAssets(join(__dirname, '..', 'public'));  
  app.setBaseViewsDir(join(__dirname, '..', 'views'));  
  app.setViewEngine('pug');  
  
  app.set('trust proxy', 1);  
  
  app.use(cookieSession({  
    name: 'session',  
    keys: ['key1', 'key2']  
  }));  
  
  //app.enableCors();  
  app.use(helmet());  
  app.use(cookieParser());  
  //app.use(csurf({ cookie: true }));  //正常是這行,但有些API POST時需要略過csrf  
  app.use(function (req, res, next) {  
    var mw = csurf({ cookie: true });  
    // console.log(req.url)  // check real get url  
    if (req.url === '/testpostcsrf') return next();  //pass csrf check  
    mw(req, res, next);  
  });  
  app.use(  
    rateLimit({  
      windowMs: 15 * 60 * 1000, // 15 minutes  
      max: 100, // limit each IP to 100 requests per windowMs  
    }),  
  );  
  
  await app.listen(3000);  
}  
bootstrap();  

layout.pug

  
doctype html  
html  
  head  
    title= title  
    meta(content= csrfToken, name='csrf-token')  
  body  
    block content  

login.pug

  
extends layout  
  
block content  
    h1 Please log in  
    if error  
        p.  
            #{error}  
    form(action="/login",method="POST")  
        input(type="hidden",name="_csrf",value=csrfToken)  
        input(type="hidden",name="challenge",value=challenge)  
        table(style="")  
            tr  
                td  
                    input(type="email",id="email",name="email",placeholder="email@foobar.com")  
                td.  
                    (Example: "foo@bar.com")  
            tr  
                td  
                    input(type="password",id="password",name="password")  
                td.  
                    (Example: "foobar")  
        input(type="checkbox",id="remember",name="remember",value="1")  
        label(for="remember") Remember me  
        br  
        input(type="submit",id="accept",value="Log in")