[英]Node.js - csurf invalid csrf token
我正在使用 npm 模块 csurf 来生成令牌。 首先,我从服务器获取令牌,然后将其用于 /register 请求。 当我用邮递员复制相同的步骤时,它似乎工作,但不幸的是不在应用程序中。 在那里它总是抛出令牌无效的错误消息
- - 服务器端 - -
csrfProtection.js
import csrf from 'csurf';
export default csrf({
cookie: true
});
路由器.js
import csrfProtection from './../../config/csrfProtection'
router.get('/csrfToken', csrfProtection, async (req, res, next) => {
return res.send(req.csrfToken());
});
router.post(
'/register',
validationHelper({ validation: registerUserValidation }),
csrfProtection,
async (req, res, next) => {
return res.send('user registered');
}
);
应用程序.js
const app = express();
app.use(cookieParser());
app.use(
cors()
);
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
- - 客户端 - -
const token = await this.$axios.$get('/csrfToken')
// token has the value 1KFmMJVz-dspX9TJo8oRInPzgDA1VY28uqQw
await this.$axios.$post(
'/register',
{
name: 'test456',
email: 'test@gmail.com',
password: '123456789'
},
{
headers: {
'csrf-token': token
}
}
)
有人遇到过同样的问题吗? 前端和后端托管在不同的域上。
您需要将它添加到cookieParser
下方的app.js
如下所示:
app.use(cookieParser())
app.use(csrfProtection)
您已成功向/csrfToken
的前端发送 CSRF 令牌,但随后您的应用程序正在/post
生成新令牌。
这是相应文档的链接。
最近修复了一个关于 csrf 令牌的 403 的类似问题。 为 get csrf 调用之后发生的每个 post 请求生成一个新的 CSRF 令牌。
我发现这是一个 CORS 问题。 我通过添加以下代码来修复:
import cors from 'cors';
const allowedOrigins = ['http://localhost:3000', 'http://localhost'];
const corsoptions: cors.CorsOptions = {
allowedHeaders: ["Origin", "X-Requested-With", "Cookie", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
credentials: true,
methods: "GET,PATCH,POST,DELETE",
origin: function (origin, callback) {
// allow requests with no origin
// (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
preflightContinue: false,
};
export const handleCors = (router: Router) =>
router.use(cors(corsoptions));
请参考 cors 包https://www.npmjs.com/package/cors"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.