Mean Stack 中的 CSRF 令牌

CSRF Token in Mean Stack

我无法将 express 的 CSRF 令牌与 Angular 的 XSRF 令牌集成。我正在使用给定的教程 https://jasonwatmore.com/post/2020/09/08/nodejs-mysql-boilerplate-api-with-email-sign-up-verification-authentication-forgot-password.

我知道代码风格很粗糙,但我需要解决这个问题。

这是我的快递代码

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));


在Angular中我在module.ts

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

请帮我解决问题

我使用不同的方法解决了我的问题。 这是 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();
})

以前我在用 https://www.npmjs.com/package/csurf 对于我的单页应用程序