avoid csrf in nodejs - node.js

I am fairly new to nodejs! I have wrote a code to avoid csrf but something is wrong and I always get the error of invalid csrf token. Can anybody help me?
This the code of my nodejs file:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var csrfProtection = csrf({ cookie: true })
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var app = express();
app.use(cookieParser())
app.use(express.static('public'));
app.get('/index.html', csrfProtection, function (req, res) {
res.render('send', { csrfToken: req.csrfToken() });
})
app.post('/process_post', urlencodedParser, csrfProtection, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, 'localhost', function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
and this is the code of my html file:
<form action = "http://127.0.0.1:8081/process_post" method = "POST">
<input type="hidden" name="_csrf" value="<%=csrfToken%>">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
I think there is something regarding setting the token in hidden value because when i try to see the source code of the page in browser the value is still <%=csrfToken%> while it should be set to a random value.

Related

What is the reason req.body is displayed as undefined?

Hi i am making a blog with node js. And now I am implementing the function to write a post, but there is a problem in this process.
new.ejs is a screen for creating a post.
new.ejs
<div>
<h2> new post </h2>
<form action="/articles" method = "POST">
<h4>title</h4>
<input required type="text" name = "title" / class='form-control'><br>
<h4>description</h4>
<textarea name="description" class = 'form-control'></textarea><br>
<h4>contents</h4>
<textarea id="mytextarea" name="contents" rows = '10'></textarea>
취소<button type = "submit" class="btn btn-primary">저장</button>
</form>
</div>
and
article.js
var express = require("express");
var app = express();
var router = express.Router();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/", function (req, res) {
res.send("article");
});
router.get("/new/home", function (req, res) {
res.render("articles/index");
});
router.get("/new", function (req, res) {
res.render("articles/new");
});
router.post("/", function (req, res) {
console.log(req.body.title);
});
module.exports = router;
Here, when req.body.title is executed, req.body becomes undefined. And in the code editor window, a sentence stating that bordyParser has been deprecated appears as the middle line is drawn. How to solve it
The EJS file is POSTing to /articles, but your POST route in the NodeJS is /.
To fix the 'body-parser is deprecated' messages, change the code as follows :-
...
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
...
to
...
app.use(express.urlencoded());
...
Body Parser is now part of Express itself.

Calling POST method by clicking a button

this is my first time when I'm setting up the server and need help. So my goal is to set up server by NodeJS and Expresss. Let's say we have an app with Admin and Users. When Admin clicks a button, it sends some data for the server, then Users can fetch the data.
So this is my server set up:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port)
I can add some post method, let's say:
app.post('/', (req, res) => ....);
So I can prepare server reaction for listening the POST method, but I have no idea how to send some data from my app by clicking an button (I mean calling this post method). I've watched a bunch of tutorials and haven't seen any real-world exercises.
To receive the POST parameters, you need the body-parser module, which you can include in your app.js like this,
var bodyParser = require('body-parser');
app.use(bodyParser.json());
And here is how you can receive your form fields which are being sent through the POST method,
app.post('/', function(req, res) {
var someField1 = req.body.some_form_field;
var someField1 = req.body.form_field1;
});
Hope this helps!
On your express server
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/", (req,res) => {
res.send("Hello");
});
On your webpage/app, You can use axios.
Lets say your express server running with localhost and port 4000.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var instance = axios.create({
baseURL: "http://localhost:4000" //use your express server's url(address) and port here
});
function onclick(){
instance.post("/").then( response => {
//response.data will have received data
}
}
</script>
You can use this function and call it on your button click
You can simply use jquery in your HTML page like this to call your api:
$("button").click(function(){
$.post("/", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
And Send data from your api:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req, res) {
var obj = {};
obj.name="hello";
obj.lname="world"
res.json(obj);
});
Example:
HTML:
Your form elements should have name (it is mandatory) to access these in post body request.
<form method="post" action="/">
<input type="text" name="Name" />
<br>
<input type="text" name="Telephone" />
<br>
<input type="submit" />
</form>
app.js
const express = require('express')
const app = express()
const port = 3000
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) => {
name = req.body.Name;
telephone = req.body.Telephone;
res.render('somefolder/index', {
name: name,
telephone: telephone,
});
// Above code is for reference if you want to load another page after post complete and get posted values in this page too.
res.end();
});

Why I still get the "Cannot POST" message?

I have a very simple html form, and express server, but I can't make the routing work. I always get "Cannot Post" message. What did I miss?
var express = require('express');
var bodyparser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
app.use(express.bodyParser());
app.get("/", function(req, res){
res.sendFile(path.join(__dirname+"/index.html"));
});
app.post("/sendform", function(req, res){
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function(){
console.log("Server is running at port: 3000");
});
<form method="post" action="http://localhost:3000/sendform">
<input type="text" name="username" />
<input type="submit" value="küldés" />
</form>
With express 4.15.3, you have to use the body parser a bit differently.
I changed your code to this and I was able to post to it:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
//app.use(express.bodyParser());
app.use(bodyParser.json({
limit: "10mb"
}));
app.use(bodyParser.urlencoded({
limit: "10mb",
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("/sendform", function (req, res) {
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function () {
console.log("Server is running at port: 3000");
});

log last time login in node

I am new to node . What I am trying to implement is to ask a user his name. When the user enters his name his session is created. On behind the time of user login is saved . Next time the user enters his name . His name plus the last time he logged in should be shown . My attempt was this
var express = require('express');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere'}));
app.use(bodyParser());
app.all('*', function findLastVisit(req, res, next) {
if (req.session.visited)
req.lastVisit = req.session.visited;
req.session.visited = Date.now();
next();
});
app.get('/', function(req, res){
var html = '<form action="/" method="post">' +
'Your name: <input type="text" name="userName"><br>' +
'<button type="submit">Submit</button>' +
'</form>';
if (req.session.userName) {
html += '<br>Your username from your session is: ' + req.session.userName + '<br> And the last time you visited was ' + req.lastVisit;
}
res.send(html);
});
app.post('/', function(req, res){
req.session.userName = req.body.userName;
res.redirect('/');
});
app.listen(1337);
console.log("server is on 1337 bro");
Unfortunately my code always displays the current time only . I think I am doing a silly mistake . can anyone point out ?
I would remove your middelware and add another variable called lastVisited like below
var express = require('express');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere'}));
app.use(bodyParser());
app.get('/', function(req, res){
var html = '<form action="/" method="post">' +
'Your name: <input type="text" name="userName"><br>' +
'<button type="submit">Submit</button>' +
'</form>';
if (req.session.userName) {
html += '<br>Your username from your session is: ' + req.session.userName + '<br> And the last time you visited was ' + req.session.lastVisited ; //LOOK here I replaced your variable with lastVisited
}
res.send(html);
});
app.post('/', function(req, res){
req.session.userName = req.body.userName;
req.session.lastVisited = req.session.visited || Date.now(); //LOOK here
req.session.visited = Date.now();
res.redirect('/');
});
app.listen(1337);
console.log("server is on 1337 bro");

Invalid Token using expressjs csurf middleware example

I've tried using the expressjs csurf example from https://github.com/expressjs/csurf When using the first example in the Readme, (using Ejs template language), the token validation works fine. When I try using the 'Ignoring Routes' example, on the 'GET /form' to 'POST /process' execution(just as I did in the first example), I get 'invalid token' on the 'POST /process'. The token is being passed to the form on the GET. Any ideas?
Is 'app.use(csrfProtection)' not working? (used in the non working example, if I remove the 'use(csrfP..' and use the methodology from the working example to use the csrf module, IE, passing 'csrfProtection' to the 'get' and 'post' methods, the second example works)
Works:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed')
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
html/ejs:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/process" method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
</body>
</html>
Does not work:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
app.set('view engine', 'ejs')
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf, after the "/api" was mounted
app.use(csrfProtection)
app.get('/form', function(req, res) {
// pass the csrfToken to the view
var tkn = req.csrfToken()
console.log(tkn)
res.render('index', { csrfToken: tkn })
})
app.post('/process', parseForm, function(req, res) {
res.send('csrf was required to get here')
})
function createApiRouter() {
var router = new express.Router()
router.post('/getProfile', function(req, res) {
res.send('no csrf to get here')
})
return router
}
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app2 listening at http://%s:%s", host, port)
})
In your second example, you are not passing the csrfProtection middleware to the POST processing chain. It should be
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('csrf was required to get here')
})

Resources