Using Angular and Nodejs as backend. csurf middleware throws Forbidden error, even if see the same _csrf token in the request cookie. My URL is: https://192.168.0.100.xip.io:64726/
Error log:
method is GET url is /
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
method is POST url is /api/login/verify
{"G_ENABLED_IDPS":"google","G_AUTHUSER_H":"0","_csrf":"XcUDRcxDPpje0nlNGdF4bZpn"}
ForbiddenError: invalid csrf token
at csrf (/Users/admin/nodejs/google-signin-server/node_modules/csurf/index.js:112:19)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
at urlencodedParser (/Users/admin/nodejs/google-signin-server/node_modules/body-parser/lib/types/urlencoded.js:100:7)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/layer.js:95:5)
at /Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/admin/nodejs/google-signin-server/node_modules/express/lib/router/index.js:335:12)
Nodejs:
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
const bodyParser = require('body-parser')
const helmet = require("helmet");
// var session = require('express-session')
const uuid = require('uuid/v4');
const app = express()
const parseForm = bodyParser.urlencoded({ extended: false });
const csrfProtection = csrf({cookie:true,secure:true,httpOnly:false})
app.use(cookieParser())
app.use((req, res, next) => {
const { method, url } = req;
console.log(" method is "+ method + " url is " + url)
logger.info('cookie', req.cookies)
next()
})
app.get('/', csrfProtection, function(req, res) {
console.log('app // get called')
// Pass the Csrf Token
tokenVal = req.csrfToken();
res.json({csrfToken: tokenVal });
res.sendFile('index.html');
});
app.post('/api/login/verify',parseForm, csrfProtection,(req, res) => {
verify(req.body.idToken)
.then((result) => {
let id = result['sub']
logger.info('id=', id)
res.send({
'payload': result
})
}).catch(logger.error)
});
Related
Hi I'm trying doing a login page, after clicking on submit I'm getting this error with express-validator version 5.3.1
req.checkBody is not a function
TypeError: req.checkBody is not a function
at Strategy._verify (C:\Users\aless\Desktop\js_cart-master\config\passport.js:67:7)
at Strategy.authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:369:16)
at authenticate (C:\Users\aless\Desktop\js_cart-master\node_modules\passport\lib\middleware\authenticate.js:370:7)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:275:10)
at C:\Users\aless\Desktop\js_cart-master\routes\user.js:39:3
at Layer.handle [as handle_request] (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:317:13)
at C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\aless\Desktop\js_cart-master\node_modules\express\lib\router\index.js:335:12)
In my app.js I have required express-validator with const validator = require('express-validator');//#5.3.1
and used it with app.use(validator());
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const passport =require('passport');
const flash = require('connect-flash');
const bcrypt = require('bcrypt');
const validator = require('express-validator');//#5.3.1
const session = require('express-session');
const MongoStore = require('connect-mongo');
const env = require('dotenv').config()
const app = express();
mongoose.connect(process.env.URI,{ useNewUrlParser: true });
require('./config/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({
secret: "key per i cookie",
saveUninitialized: false,
resave: false,
store: MongoStore.create({
mongoUrl: process.env.URI,
autoRemove: 'disabled'
}),
cookie: { maxAge:30000,secure:false }
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//verify if authenticated
app.use((req, res, next)=>{
res.locals.login =req.isAuthenticated();
//access sessions through templates
res.locals.session = req.session;
next();
});
//routes
app.use('/', require('./routes/index'));
app.use('/user', require('./routes/user'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Using this express-validator version I got this error when submit, using last express-validator version I get same error in console.
Why I'm getting this error??
The reason is the way you are requiring it.
const { body, validationResult } = require('express-validator');
In your code you can make these changes and try:
const { validationResult } = require('express-validator');//#5.3.1
.
.
.
app.use(validationResult());
Note: check this link for more information.
I got "TypeError: res.send is not a function" this error in the given code
const express = require('express');
const bodyParser=require('body-parser');
const app=express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/' , (req , res)=>{
res.sendFile(__dirname+"/index.html")
})
app.post('/' , (req , res)=>{
// console.log(req.body);
var num1=req.body.num1;
var num2=req.body.num2;
var res=num1+num2;
res.send('Ans is: '+res);
});
app.listen(3000,function(){
console.log('running');
});
plzz help me to fix this :(
and the error looks like this:-
TypeError: res.send is not a function
at C:\Users\ADMIN\Desktop\calculator\calculator.js:16:8
at Layer.handle [as handle_request] (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ADMIN\Desktop\calculator\node_modules\express\lib\router\index.js:275:10)
at C:\Users\ADMIN\Desktop\calculator\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\Users\ADMIN\Desktop\calculator\node_modules\raw-body\index.js:224:16)
You overwrite res with your own local variable:
var res=num1+num2;
This "shadows" the res in your function declaration.
you just override res again in the above line..
var res=num1+num2;
change this to anything else like
var result =num1+num2;
res.send('Ans is: '+result);
I have this route:
var express = require('express');
var multer = require('multer');
const upload = multer();
module.exports = (function () {
var router = express.Router();
router.post('/avatar/:user', upload.single('avatar'), function (req, res, next) {
var file = req.file; // file passed from client
var meta = req.body; // all other values passed from the client, like name, etc..
console.log(file);
console.log(meta);
res.json({
success: true
});
});
return router;
})();
And when I try to post to it using Postman with header 'Content-Type : application/x-www-form-urlencoded' and in body 'form-data' File (image), the express crashes with error:
Error
at readStream (F:\Web\WorkoutFocus_Server\node_modules\raw-body\index.js:196
:17)
at getRawBody (F:\Web\WorkoutFocus_Server\node_modules\raw-body\index.js:106
:12)
at read (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib\read.js:76:
3)
at urlencodedParser (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib
\types\urlencoded.js:115:5)
at Layer.handle [as handle_request] (F:\Web\WorkoutFocus_Server\node_modules
\express\lib\router\layer.js:95:5)
at trim_prefix (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\i
ndex.js:317:13)
at F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\Web\WorkoutFocus_Server\node_modules\express\
lib\router\index.js:335:12)
at next (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js
:275:10)
at jsonParser (F:\Web\WorkoutFocus_Server\node_modules\body-parser\lib\types
\json.js:112:7)
at Layer.handle [as handle_request] (F:\Web\WorkoutFocus_Server\node_modules
\express\lib\router\layer.js:95:5)
at trim_prefix (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\i
ndex.js:317:13)
at F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (F:\Web\WorkoutFocus_Server\node_modules\express\
lib\router\index.js:335:12)
at next (F:\Web\WorkoutFocus_Server\node_modules\express\lib\router\index.js
:275:10)
at cors (F:\Web\WorkoutFocus_Server\node_modules\cors\lib\index.js:185:7)
Does this have something to do with file size or multipart/form-data perhaps?
I tried to set the bodyparser.json limit to '50mb', but no difference.
Looks like a simple task, but I can not find out the error in my code.
app.js
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var routes = require('./routes')(app);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('view engine', 'jade');
app.set('views', './views');
app.use(express.static('./public'));
app.listen(3000, function() {
console.log('hello');
console.log('express server listening on port:' + 3000);
});
index.jade
html
head
title Welcome
body
p Enter your name and email address to become a member.
form(action='/signup', method='post')
div
label Name
input(type='text', name='name')
div
label Email
input(type='text', name='email')
div
input(type='submit')
routes.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index');
});
app.post('/signup', function(req, res) {
console.log(req);
console.log(req.body);
var name = req.body.name;
var email = req.body.email;
console.log('Name: ' + name);
console.log('Email: ' + email);
res.json(req.body);
});
};
When I post the form I get the error:
TypeError: Cannot read property 'name' of undefined
at /Users/demas/temporary/express/1/routes.js:11:22
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at /Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:330:12)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:271:10)
at expressInit (/Users/demas/temporary/express/1/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
In the console I can see the req.body is undefined. Why?
You need to do your configuration before you do the routing, so moving down this line :
var routes = require('./routes')(app);
Below this :
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
... should work.
I am trying to create a server for an app with a node JS server on AWS(not sure how relevant that is) and I am testing it with Postman. For some reason my hello world function, which is just a GET works perfectly but my POST to create a user keeps giving me this error:
TypeError: Cannot read property 'username' of undefined
at app.get.params.QueueUrl (/home/ec2-user/Outfitr/Server/index.js:40:29)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:110:13)
at Route.dispatch (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:91:3)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at /home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:267:22
at Function.proto.process_params (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:321:12)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:261:10)
at serveStatic (/home/ec2-user/Outfitr/Server/node_modules/express/node_modules/serve-static/index.js:59:14)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
Here is my code:
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World (Finally)');
});
app.post('/create_user', function( request, response) {
process.stdout.write("WTF");
create_user( request.body.username, request.body.password, request.body.firstname, request.body.lastname, request.body.gender, request.body.latitude,
request.body.longitude, request.body.description, request.body.city,
request.body.state_province, request.body.country, request.body.email,
request.body.phone_number);
response.send('IT WORKED!');
});
function create_user( username, password, firstname, lastname, is_brand, gender,
description, city, state_province, country, birthday) {
messageBody = {"username":username, "password":password, "firstname": firstname,
"lastname":lastname, "is_brand":is_brand, "gender":gender, "city":city,
"state-province":state_province, "country":country, "birthday":birtyhday};
queueUrl = DAO_QUEUE_URL;
sendSQSMessage( JSON.stringify(messageBody),queueUrl);
}
What could be wrong?
Make sure that you are using the x-www-form-urlencoded tab in postman. I've fallen for that a few times.
Also, make sure you are using the body-parser package.
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var bodyParser = require('body-parser');
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
// Add the middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
So I think that you are getting the error because there is no middleware setting up a req.body object for you, bodyParser should do the trick.