How do I protect a post call from a angular2 application to a Express server?
In my angular2 application I have a the following HTTP Post.
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const data = {
email: this.form.value.email
};
this.http.post('http://localhost:8080/api/user/email', data, {
headers: headers
})
Now I want to make sure that only my angular 2 application can make the post call to the user api. I did some research about csrf in combination with Express and Angular 2. In my Angular 2 application I made the following implementation to the app.module.ts file.
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '#angular/http';
providers: [ {
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
} ]
I think this is the right way to implement a XSRFStrategy to Angular 2?
For the implementation in Express I followed a few tutorials, but without any success. Most of the time I received:
ForbiddenError: invalid csrf token
How do I implement the CSRF part in my Express api. Here is my Express config:
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.use(function (req, res, next) {
console.log('Something is happening.');
res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "POST");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.setHeader('Content-Type', 'application/json');
next();
});
app.use('/api', router);
router.post('/user/email', function (req, res) {
..... [how to make sure that this post can only be fired from my angular 2 application ]
}
Update #1
Did some more research and found the following in the Angular 2 docs:
//By default, Angular will look for a cookie called `'XSRF-TOKEN'`, and set
//* an HTTP request header called `'X-XSRF-TOKEN'` with the value of the cookie on each request,
So in my Express application I added the following parts:
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600000
}
var csrfProtection = csrf({
cookie: cookieOptions
})
and in the post route I implemented the protection as follow:
router.post('/user/email', csrfProtection, function (req, res) {
console.log('post incomming');
}):
I got the following response headers back
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:http://localhost:4200
Connection:keep-alive
Content-Length:1167
Content-Type:text/html; charset=utf-8
Date:Mon, 21 Nov 2016 20:07:12 GMT
set-cookie:XSRF-TOKEN=O4JKkjAZRik2H7ml0DoxDc8s; Max-Age=3600000; Path=/
X-Content-Type-Options:nosniff
X-Powered-By:Express
And the request headers:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Connection:keep-alive
Content-Length:38
content-type:application/json
Host:localhost:8080
Origin:http://localhost:4200
Referer:http://localhost:4200/profile/users
How to implement CSRF protection with Angular2 and Express
By default, Angular will look for a cookie called 'XSRF-TOKEN', and set
an HTTP request header called 'X-XSRF-TOKEN' with the value of the cookie on each request.
To make sure that our backend can set a XSRF-TOKEN cookie, we have to proxy our calls to the api running on port 8080. We can do that with a proxy.config.json file.
{
"/api/*" : {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
And in our package.json file we modify the scripts/start function to use our proxy.config.json file:
"scripts": {
"start": "ng serve --proxy-config proxy.config.json",
}
Now every time we run npm start our calls to /api are proxied to localhost:8080. Now we are ready to make a post call to our api server.
In our component we make a http post call and we set the headers to use content-type application/json.
ourfunction() {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
data = { key:value }
this.http.post('/api/user/email', data, {
headers: headers
}).subscribe( (resp: any) => console.log('resp', resp));
}
That is everything we need to do at the Angular2 side. Now we are implement the Express side.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var cors = require('cors')
We initialise our app and defining some middleware to use in our application.
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600
}
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
Here we are setting the options to use for csrf and cors middleware.
const port = process.env.PORT || 8080; // set our port
const csrfProtection = csrf({ cookie: cookieOptions })
const router = express.Router();
Implementing the middelware. The order is very important to get the correct results.
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(csrfProtection);
router.use(function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
next();
});
Thats all we need to do on the Express side. Now we can secure our post calls with a CSRF token.
Compleet express server file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var cors = require('cors')
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600
}
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
const port = process.env.PORT || 8080; // set our port
const csrfProtection = csrf({ cookie: cookieOptions })
const router = express.Router();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(csrfProtection);
router.use(function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
next();
});
router.post('/user/email', function (req, res) {
console.log('post incomming');
console.log('req', req.body);
res.send('testing..');
});
app.listen(port);
console.log('Magic happens on port ' + port);
Related
Im using AWS Amplify to generate Node Express rest API endpoints.
I recently added a new endpoint, but I keep getting undefined in the request body, and I can't figure out where I might have miss-configured my application.
App.js
var express = require("express");
var bodyParser = require("body-parser");
var awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");
// declare a new express app
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(awsServerlessExpressMiddleware.eventContext());
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
var aws = require("aws-sdk");
const https = require("https");
app.post("/refresh", function(req, res){
console.log(JSON.stringify(req.body));
// {}
console.log(JSON.parse(req.body));
//Error: unexpected token o in JSON at position 1
});
I'm testing this in the AWS console with this payload
{
"path": "/refresh",
"httpMethod": "POST",
"header": "{\"content-Type\":\"application/json\"}",
"body": "{\"Username\":\"test\"}"
}
Set header as
"Content-Type: application/json"
I am new to Express and I have problems with sending cookies.
I made a simple express app that needs to set a cookie to the browser. This is the server:
const express = require('express');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const app = express();
//app.use(cors());
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['http://127.0.0.1:5500']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
res.append('Access-Control-Allow-Credentials', 'true');
next();
});
app.use(cookieParser());
app.use(express.json());
const PORT = 9000;
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.cookie('testCookie', 'random value', {httpOnly: false, secure: false});
res.send({user: "test", password: "test123"});
})
app.listen(PORT, console.log(`Server started on port ${PORT}`));
So it successfully sends to the browser the testCookie on request with fetch:
let response = await fetch('http://localhost:9000/', {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json());
console.log(response);
After the request the cookie is successfully send because is in the Chrome cookie tab but document.cookie returns an empty string. And also when i make request to a page the request doesnt contains the Cookie header.
How can I make the cookie to be visible to document.cookie and also to the browser to send his Cookie header?
I strongly suggest you to use an npm package: jsonwebtoken, https://www.npmjs.com/package/jsonwebtoken
This way it's much cleaner:
const jwt = require ('jsonwebtoken');
// Create login logic here (check password etc.);
const token = jwt.sign(user, secret, expiration);
res.status(201).json({
status: 'success',
token
});
Try using JSON format instead of res.send since you have a body parser in place already and it's a best practice in modern APIs.
I am trying to use the Cors middleware but it is not working
I followed the simple instructions in the documentation, but I am still getting this dreaded error.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
Can anyone help me? This is the index.js file of my backend API, where I try to implement the middleware.
const express = require('express');
const passport = require('passport');
const http = require('http');
const morgan = require('morgan');
const LocalStrategy = require('passport-local').Strategy;
let path = require('path');
let mongoose = require('mongoose');
let config = require('./config/config');
let bodyParser = require('body-parser');
let recipeRouter = require('./routes/recipeRouter');
let userRouter = require('./routes/userRouter');
/// Here, I required the middleware.
let cors = require('cors');
const app = express();
// set up DB
mongoose.connect(config.mongoUrl);
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
// Set up App
app.use(morgan('combined'));
/*
This is another attempt to get this to work. Tried it, but didn't work.
app.use(function(req, res, next){
const origin = req.get('origin');
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
/// res.header('Access-Control-Allow-Methods', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma, x-auth');
});
*/
/// Here I try to apply the middleware.
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' }));
// !! NEW !! //
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', userRouter);
app.use('/recipes',recipeRouter);
// Set up Server
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
Can anyone help? Am I missing something?
I'm making a PATCH request from a client running on localhost:3000 with the following code:
axios.patch(
"http://localhost:3090/v1/users/etc/etc/etc", {
name,
url,
}, {
headers: {
authorization: AUTH_TOKEN()
}
}
)
To a server configured as follows:
var app = express();
var cors = require('cors');
//etc
//var whitelist = [
// 'http://localhost:3000',
// 'localhost:3000'
//];
//passing this to cors() doesn't help
//var globalCorsOptions = {
// origin: function(origin, callback) {
// callback(null, whitelist.indexOf(origin) !== -1);
// }
//};
app.use(morgan('combined'));
app.use(cors());
app.options('*', cors());
app.use(bodyParser.json({type:'*/*'}));
app.use('/v1', router);
var port = process.env.PORT || 3090;
var ip = process.env.IP || 'localhost';
var server = http.createServer(app);
server.listen(port, ip);
But the request just hangs. I can do POST/GET fine, but not DELETE/PATCH. The preflight happens fine but the actual request following just sits "stalled" indefinitely. Here's the headers for each request:
Sorry to ask this pretty standard question, but I've tried everything.
EDIT:
Added the following to router (still not working):
var router = express.Router();
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers", "PATCH,DELETE,OPTIONS,GET,POST");
next();
});
The actual error:
On the server you have to add following header to the response:
headers.Add("Access-Control-Allow-Headers", "PATCH,DELETE,GET,POST");
Actually all HTTP methods you want to allow.
I am having a strange issue with cookies in my node app. It is hosted on Heroku and I use JSON Web Tokens stored in a cookie that is authenticated by my express middleware. When I login on my Macbook pro, the cookie is successfully stored. However, when I use Linux Mint desktop, or an Android tablet, the site logs in but then redirects on protected routes and the cookie is never set.
This is where the cookie is set on login:
let token = jwt.sign({
username: user.username,
email: user.email
}, config.privateKey, {
expiresIn: '7d'
});
let userResponse = {
success: true,
message: 'Successfully logged in!',
id: user._id,
email: user.email,
username: user.username
}
// set cookie for 7 days
res.cookie('auth_token',
token,
{maxAge: 604800000, path: "/"}).json(userResponse);
Here is my server.js file:
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const env = process.env.NODE_ENV || "development";
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const config = require('./app/config/config.js');
process.env.PWD = process.cwd();
// Establish connection with MongoDB
mongoose.connect(config.db.connectString);
app.use(cookieParser());
// Allowing X-domain request
var allowCrossDomain = function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control");
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('public'));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', () => {
console.log('Connected to sondage database');
});
// ===== Import Routers ======
const userRouter = require('./app/routes/user.routes')(express, app);
const pollRouter = require('./app/routes/poll.routes')(express, app);
const authRouter = require('./app/routes/auth.routes')(express, app);
app.use('/api/users', userRouter);
app.use('/api/polls', pollRouter);
app.use('/api/', authRouter);
// For all other requests, use React Router
app.get('*', function (request, response){
response.sendFile(process.env.PWD + '/public/index.html');
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server running');
});
EDIT I have traced this down to a http vs https issue. If I use https in the request, the cookies work. Otherwise cookies aren't set. So I need a way to force the user to do HTTPS.
I was able to fix this using the heroku-ssl-redirect node package. This takes requests and forces the browser to use https for each request.