我试图在Express.js应用程序上使用lusca设置CSRF保护。不是这样的:
this.app.use(lusca({
csrf: {
cookie: {name: '_csrf'}
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
nosniff: true,
referrerPolicy: "same-origin",
xframe: "SAMEORIGIN",
xssProtection: true,
}));
在客户端,如下:
const res = await axios.post(`${Constants.apiUrl()}/${Constants.paths.login}`,
credentials, {
withCredentials: true,
xsrfCookieName: '_csrf'
});
在服务器端,我还设置了一些标头,以便能够根据请求发送Cookie-res.header('Access-Control-Allow-Credentials', 'true')
。
[我可能缺少CSRF保护工作原理的重要部分。现在每次有了响应,我都会得到新的csrf token
,但这意味着我的新HTTP POST请求发送了已经过时的先前令牌。我缺少什么?
最后,经过3小时的测试,我发现了问题。您需要添加csrf的secret
。另外,如果您使用的是Angular,则需要将angular: true
添加到csrf中。
this.app.use(lusca({
csrf: {
cookie: {name: '_csrf'},
secret: 'qwerty'
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
nosniff: true,
referrerPolicy: "same-origin",
xframe: "SAMEORIGIN",
xssProtection: true,
}));