Try to search your question here, if you can't find : Ask Any Question Now ?

invalid csrf token when using ajax

HomeCategory: stackoverflowinvalid csrf token when using ajax
Avatarbhawya asked 3 months ago

I started learning NodeJs and pushed by my knowledge of js I start writing some code for create the user registration logic.

Essentially I have configured ExpressJS in the following way:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');

app.use(session({
    secret: 'foofofoo',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(csrf());
app.use(function (req, res, next) {
    var csrfToken = req.csrfToken();
    res.cookie('XSRF-TOKEN', csrfToken);
    res.locals.csrfToken = csrfToken;
    next();
});

then I created a basic .ejs view for the user registration:

<meta name="csrf-token" content="<%= csrfToken %>">
<p>
    <label class="w3-text-blue"><b>User Name</b></label>
    <input class="w3-input w3-border" id="uname" name="uname" type="text"></p>
<p>
    <label class="w3-text-blue"><b>Password</b></label>
    <input class="w3-input w3-border" id="upass" name="pass" type="text"></p>
<p>
    <button class="w3-btn w3-blue" id="regForm">Register</button></p>

the csrfToken is taken by the middleware above.
When the user press the button regForm this code is called:

$("#regForm").click(function () {
    let uname = $("#uname").val();
    let upass = $("#upass").val();
    let token  = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    let regData = 
    {
        'name': uname, 
        'pass': upass 
    };

    $.ajax({
        type: 'POST',
        url: '/registerUser',
        headers: {"X-CSRF-Token": token },
        data: regData,
        success: function (data) {
            $("#mainDiv").html(data);
        }
    });
});

and looking at the ajax request the token is passed correctly:

enter image description here

but inside the console I get:

ForbiddenError: invalid csrf token

this is the route method:

app.post('/registerUser', function(req, res, next){
    //todo
});
1 Answers
Best Answer
AvatarFernando answered 3 months ago
Your Answer

5 + 0 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com