Express CSRF token validation

后端 未结 3 1818
轻奢々
轻奢々 2020-12-17 00:44

I\'m having issues with CSRF tokens. When I submit a form, a new XSRF-TOKEN is being generated but I think I\'m generating two different tokens, I\'m kinda conf

3条回答
  •  孤城傲影
    2020-12-17 01:11

    Below code is working for me. Let me know in case you still face issue.

    As mentioned that you wish to use cookies, you have make csurf aware that you are using cookies for setting the CSRF token.

    Step1: Configuration

    var csrf = require('csurf');
    var cookieparser= require('cookie-parser'); 
    
    //cookieparser must be placed before csrf 
    app.use(bodyparser.urlencoded({extended:false}));
    app.use(cookieParser('randomStringisHere222'));
    app.use(csrf({cookie:{key:XSRF-TOKEN,path:'/'}}));
    
    //add the your app routes here
    app.use("/api", person);
    app.use("/", home);
    

    Step2: In the route,

    res.render('myViewPage',{csrfTokenFromServer:req.csrfToken()}); 
    

    Step3: Include a hidden field in the HTML for csrf token Example:

    /> First name:

    Last name:


提交回复
热议问题