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 confused. There's also a token called _csrf, so I see two different cookies in developer tools (XSRF-TOKEN and _csrf), _csrf doesn't change after a post.
What I want to do is to generate a new token for each post request and check whether it's valid or not. One thing I know that I should do it for security, but I stuck.
It has been a long day and I'm new into Express and NodeJS.
Here's my current setup.
var express = require('express')
, passport = require('passport')
, flash = require('connect-flash')
, utils = require('./utils')
, csrf = require('csurf')
// setup route middlewares
,csrfProtection = csrf({ cookie: true })
, methodOverride = require('method-override')
, bodyParser = require("body-parser")
, parseForm = bodyParser.urlencoded({ extended: false })
, cookieParser = require('cookie-parser')
, cookieSession = require('cookie-session')
, LocalStrategy = require('passport-local').Strategy
, RememberMeStrategy = require('../..').Strategy;
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('ejs', require('ejs-locals'));
app.use(express.logger());
app.use(express.static(__dirname + '/../../public'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(flash());
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('remember-me'));
app.use(app.router);
app.use(csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals.csrftoken = req.csrfToken();
next();
});
Routes
app.get('/form', csrfProtection, function(req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken()});
});
app.post('/process', parseForm, csrfProtection, function(req, res) {
res.send('data is being processed');
});
send.ejs (/form GET)
<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>
Based on the amount of code you shared, I will mention a few things that don't look quite right to me:
1 . You may need to swap the lines below so that csrf runs before the routes.
app.use(csrf());
app.use(app.router);
2 . The csrftoken setup needs to also be placed before the routes.
app.use(csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals.csrftoken = req.csrfToken();
next();
});
app.use(app.router);
3 . You'll need to use locals.csrftoken in your form:
<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>
the token in the cookie will be completely different than the one in the express session. you want to check for one or the other not both.
i would disable the cookies entirely! as it worked for me.
var csrfProtection = csurf({ cookie: false });
the author mentions it here
https://github.com/expressjs/csurf/issues/52
next you want to the "X-CSRF-Token" to the header on ajax post found here:
Express.js csrf token with jQuery Ajax
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:
<form action="/api/person" method="POST">
<input type="hidden" name="_csrf" value=<%=csrfTokenFromServer %> />
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
When we set csrf cookie it has default key _csrf. We can override it. So in my case I gave same name to cookie like this.
const csrf = csurf({cookie:{key:'XSRF-TOKEN'}});
app.get('/csrf-token', csrf, (req: Request, res: Response, next: NextFunction) => {
const newToken = req.csrfToken();
res.cookie('XSRF-TOKEN', newToken, {
httpOnly: true,
sameSite: 'strict',
secure: process.env.NODE_ENV === 'production',
});
res.json({ csrfToken: newToken });
});
I dont know if you resolved the issue but its still will help if someone else looking for it.
Related
I am trying to output the value of title which i entered in the form in the /Add-Product link
Here is my app.js code
const http= require('http');
const path= require('path');
const express= require('express');
const app= express();
app.set('view engine', 'ejs');
app.set('views', 'Views');
app.use(express.static(path.join(__dirname, 'Public')));
app.get('/', (req, res, next)=>{
res.render('shop');
});
app.get('/admin', (req, res, next)=>{
res.render('admin');
});
app.get('/add-product', (req, res, next)=>{
res.render('addProduct');
});
app.post('/add-product', (req, res, next)=>{
console.log(req.body.title); //uable to display value of req.body.title
res.redirect('/');
});
app.listen(3000);
form part of the addProduct.ejs
<main>
<form action="/add-product" method="POST">
<p>Title</p>
<input type="text" name="title" id="title"/>
<p>Price</p>
<input type="text" name="price"/>
<p>Description</p>
<input type="text" name="description"/>
<button type="submit">Submit</button>
</form>
</main>
Unable to figure why the req.body.title is throwing an error as:Cannot read property 'title' of undefined
Please guide me on what i am missing.
By default, form submits the data to server in the content type of application/x-www-form-urlencoded. So you need to configure node js to receive this type of content. Use bodyParser to read the request body with json and encoded content.
Usage:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
I am trying to implement csrf tokens for the first time and i am running into issues. I've been working at it for a few hours and haven't been able to solve it. Below is the error I am getting:
ForbiddenError: invalid csrf token
app.js
const express = require('express')
const app = express()
const router = require('./router')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const flash = require('connect-flash')
const dotenv = require('dotenv')
const csrf = require('csurf')
dotenv.config()
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use(express.static('public'))
app.use(cookieParser('secret'))
app.use(session({
secret: 'secret',
cookie: {maxAge: null},
resave: false,
saveUninitialized: false
}))
app.use(flash())
app.set('views', 'views')
app.set('view engine', 'ejs')
app.use(csrf())
app.use(function(req, res, next) {
res.locals.csrfToken = req.csrfToken()
next()
})
app.use('/', router)
app.use(function (req, res, next) {
res.status(404).render('404')
})
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).render('404')
})
app.listen(process.env.PORT)
router.js
const express = require('express')
const multer = require('multer')
const multerConfigOpts = require('./multer.config')
const router = express.Router()
const userController = require('./controllers/userController')
const csrf = require('csurf')
var csrfProtection = csrf({ cookie: true })
// set multer configuration options
const upload = multer(multerConfigOpts)
router.get('/', userController.home)
router.get('/about', userController.about)
router.get('/employer', userController.employer)
router.get('/jobSeeker', userController.jobSeeker)
router.get('/ourProcess', userController.process)
router.get('/contact', userController.contactUs)
// Talent Request Post related routes
router.post('/talentrequest',upload.none() ,userController.requestTalent)
// Job Request Post related routs
router.post('/jobrequest', csrfProtection, upload.single('resume'), userController.requestJob)
module.exports = router
Example of my form:
<form action="/jobrequest" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn--form-submit">Submit</button>
</div>
</form>
There are more data fields, I just didn't want to bloat the question with unnecessary code. I've been reading that others are having similar issues when using multipart in the form, but I can't seem to figure it out.
I know that my token is being generated inside the form but I'm not sure if its being passed through properly. Any help or pointers would be appreciated. Thank you
So I was able to find a work around solution by adding the following to my form and removing the input hidden field from my form
form action="/talentrequest/*?_csrf=<%= csrfToken %>*" method="POST" enctype="multipart/form-data">
Everything works as it should. Can anyone explain the potential risks involved with this?
I am trying to use passport authentication with a local strategy provided by passport-local-mongoose to authenticate a user. If the user is authenticated, then he is allowed to view the /secret route, else he gets a bad request message (provided by passport).
The weird part is that the authentication works for the login POST route, which successfully redirects to the /secret page upon correct credentials. But on redirection, the user gets a bad request which means that authentication fails at the /secret route. This is very confusing as the user could only be redirected to /secret if he was successfully authenticated upon login, but upon redirection to /secret, authentication fails and a bad request error is sent.
User Schema:
const mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
const userSchema = new mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
module.exports = new mongoose.model("User", userSchema);
Server Configuration:
const express = require("express"),
mongoose = require("mongoose"),
passport = require("passport"),
bodyParser = require("body-parser"),
LocalStrategy = require("passport-local"),
expressSession = require("express-session");
const User = require("./models/user");
const app = express();
app.set("view engine", "ejs");
app.use(
expressSession({
secret: "Lorem Ipsum",
resave: false,
saveUninitialized: false
})
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/auth-test", {
useNewUrlParser: true,
useUnifiedTopology: true
});
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Login and Secret Routes:
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/secret",
failureRedirect: "/register"
})
);
app.get("/secret", passport.authenticate("local"), (req, res) => {
res.render("secret");
});
Login form in case it is needed, used on the /login GET route:
<form action="/login" method="POST">
<input type="text" placeholder="Username" name="username" autocomplete="off" />
<input type="password" placeholder="Password" name="password" autocomplete="off" />
<button type="submit">Submit</button>
</form>
Checking passport-local code, it seems that Authenticate() is used to verify the user's credentials (username, password), so basically you'll only need to use it in /login route.
To verify if the user is authorized to access a protected route, you can use req.isAuthenticated() instead.
Example:
app.get("/secret", (req, res) => {
if (!req.isAuthenticated()) {
return res.sendStatus(401);
}
res.render("secret");
});
I'm hoping someone can help with showing flash messages in Express via a Handlebars view (which uses the bootstrap markup).
In app.js I have the below modules and middleware to try and get flashes working
//require modules
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const hbs = require('express-handlebars');
const session = require('express-session');
const flash = require('connect-flash');
const routes = require('./routes/index');
const app = express();
// view engine setup
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout',layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(flash());
app.use((req, res, next) => {
res.locals.h = helpers;
res.locals.flashes = req.flash();
res.locals.user = req.user || null;
res.locals.currentPath = req.path;
next();
});
app.use('/', routes);
module.exports = app;
and a route
router.post('/store/add', storeController.createStore);
which has the controller function
exports.createStore = async (req, res) => {
const store = new Store(req.body);
await store.save();
req.flash('error', 'leave a review');
console.log('my-messages',req.flash());
res.redirect('/');
};
when I create a new store and am redirected to homepage the console.log shows the correct value my-messages { error: [ 'leave a review' ] } but I cannot get it into the view
my homepage ('/') view is
<h1>{{title}}</h1>
<p>Hi! Welcome to {{title}} </p>
<p>This page was built by {{created}}</p>
{{#if message}}
<div class="alert alert-danger">{{message}}</div>
{{/if}}
{{#if errors}}
{{#each errors}}
<div class="error">
{{msg}}
</div>
{{/each}}
{{/if}}
but nothing shows up. I've read quite a few similar questions on SO, but can't seem to get this right.
Any help much appreciated.
OK, so this is how I've worked things based on https://gist.github.com/brianmacarthur/a4e3e0093d368aa8e423 from this https://stackoverflow.com/a/28221732/1699434 answer.
After app.use(flash()) in app.js I added:
app.use(function(req, res, next){
// if there's a flash message in the session request, make it available
in the response, then delete it
res.locals.sessionFlash = req.session.sessionFlash;
delete req.session.sessionFlash;
next();
});
In my routes file (index.js) I added the example in the gist:
router.all('/session-flash', function( req, res ) {
req.session.sessionFlash = {
type: 'info',
message: 'This is a flash message using custom middleware and express-session.'
}
res.redirect(301, '/');
});
Then I created a handlebars partial message.hbs (which makes use fo the contains helper from npmjs.com/package/handlebars-helpers:
{{#if sessionFlash.message}}
<div id="flash-messages" class="container">
{{#contains sessionFlash.type "info"}}
<div class="alert alert-info">
{{{sessionFlash.message}}}
</div>
{{/contains}}
{{#contains sessionFlash.type "success"}}
<div class="alert alert-success">
{{{sessionFlash.message}}}
</div>
{{/contains}}
{{#contains sessionFlash.type "warning"}}
<div class="alert alert-warning">
{{{sessionFlash.message}}}
</div>
{{/contains}}
{{#contains sessionFlash.type "error"}}
<div class="alert alert-danger">
{{{sessionFlash.message}}}
</div>
{{/contains}}
</div>
{{/if}}
I can then include this in my other handlebars templates {{> message}}. This gives me flash messages carrying bootstrap styling.
Unfortunately I'm not able to send multiple flashes at the same time (either of the same or different types) but I think this is discussed in https://gist.github.com/brianmacarthur/a4e3e0093d368aa8e423 anyway as a limitation of the middleware approach. As I learn more maybe I'll address this but I don't have a use case for multiple flash messages at the moment anyway :)
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.
app.js:
var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();
app.engine('html', consolidate.nunjucks);
app.set('view engine', 'html');
app.set('views', './views');
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(3055);
module.exports = app;
routes/index.js:
const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
router.post('/addsubject', function(req, res, next){
Patient.create(req.body).then(function(patient){
res.redirect('/profile');
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
} else {
return next(err);
}
}).catch(function(error){
res.send(500, error);
});
});
router.get('/profile', function(req, res, next){
res.render('./profile.html');
});
router.get('/addsubject', function(req, res, next){
// .... do something here ..
});
module.exports = router;
I have the <form action="/addsubject" method="post"> in my index.html file.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dabl Demographic</title>
<body>
<h2>Add Subject</h2>
<form action="/addsubject" method="post">
<label for="fname">First Name: </label>
<input type="text" name="fname" id="fname">
<br>
<label for="sname">Second Name: </label>
<input type="text" name="sname" id="sname">
<br>
<label for="dob">dob: </label>
<input type="text" name="dob" id="dob">
<br>
<label for="laterality">Laterality: </label>
<input type="text" name="laterality" id="laterality">
<br>
<button>Submit</button>
</form>
</body>
</html>
You pass wrong function (error handling function) to the POST route.
Just remove first "err" param from the function like this:
router.post('/addsubject', function(req, res, next){
Use body-parser middleware before app.router
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
Problem solved:
}).catch(function(err){
if(error.name === "SequelizeValidationError"){
next(err); //next(err); called inide this block no more 404 error
}
User input is now succesfully passed through the body-parser.