Search code examples
node.jsangularexpresscsrf-tokenx-xsrf-token

CSRF Token in Mean Stack


I am not able to integrate CSRF token of express with XSRF TOKEN of Angular. I am using the given tutorial https://jasonwatmore.com/post/2020/09/08/nodejs-mysql-boilerplate-api-with-email-sign-up-verification-authentication-forgot-password.

I know code is in rough style but I need to solve the issue.

Here is my code of express

server.js(main)

require('rootpath')();
const express = require('express');
const app = express();
const helmet = require("helmet");
const bodyParser = require('body-parser');

var cookieParser = require('cookie-parser')
var csrf = require('csurf')


const cors = require('cors');
const errorHandler = require('_middleware/error-handler');

app.use(cookieParser());
app.use(csrf({ cookie: true }))


app.use(helmet({ dnsPrefetchControl: { allow: true }}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());



app.all('*', function (req, res) {
    res.cookie('XSRF-TOKEN', req.csrfToken())
    
  })

app.use(cors({ origin: (origin, callback) => callback(null, true), credentials: true }));



// api routes
app.use('/accounts', require('./accounts/accounts.controller'));

// swagger docs route
app.use('/api-docs', require('_helpers/swagger'));

// global error handler
app.use(errorHandler);

// start server
const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000;
app.listen(port, () => console.log('Server listening on port ' + port));


In Angular I have added in XSRF TOKEN in module.ts

 imports: [
        BrowserModule,
        ReactiveFormsModule,
        HttpClientModule,
        HttpClientXsrfModule.withOptions({
          cookieName: 'XSRF-TOKEN',
          headerName: 'X-XSRF-TOKEN'
        }),
        AppRoutingModule
    ],

Kindly Help me to sort out the issue


Solution

  • I have used different which solved my problem. here is the link https://www.npmjs.com/package/express-csrf-double-submit-cookie

    const cookieParser = require('cookie-parser')
    const csrfDSC = require('express-csrf-double-submit-cookie')
    const express = require('express')
     
    // create middleware
    const csrfProtection = csrfDSC();
     
    const app = express();
    app.use(cookieParser());
     
    // middleware to set cookie token 
    app.use(csrfProtection)
     
    // protect /api
    app.post('/api', csrfProtection.validate, function (req, res) {
      res.status(200).end();
    })
    

    previously I was using https://www.npmjs.com/package/csurf for my single page application