使用axios防止帖子来自域以外的来源



我正在开发我的第一个网站,并使用axios向后端发送post/get请求。我在前端使用React,在后端使用node/express。我想知道是否有一种方法可以阻止来自我的网站以外的来源的帖子。

例如,如果我通过邮递员提出这个确切的请求,我仍然可以发表评论,这意味着有人可以用自己以外的名字和身份证发表评论。

以下是在前端提出的一个典型的帖子请求:

axios.post('/api/forumActions/postComment', {}, {
params: {
postUserID: this.props.auth.user.id,
name: `${this.props.auth.user.firstName} ${this.props.auth.user.lastName}`,
commentContent: this.state.commentContent,
respondingToPost: this.state.postID,
respondingToComment: this.state.postID
}
})

以下是它在后端上的处理方式

app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(passport.initialize());
require("./config/passport")(passport);
app.post('/postComment', (req, res)=>{
var commentData={
postUserID: req.query.postUserID,
name: req.query.name,
commentContent: req.query.commentContent,
respondingToPost: req.query.respondingToPost,
respondingToComment: req.query,respondingToComment
}
//Write commentData to database
})
const port = process.env.PORT || 80;
const server = app.listen(port, () => console.log(`Server running on port ${port} !`));

我想知道我是否可以做些什么来加强安全,防止从任何地方发出邮件请求?

您可以使用cors来实现这一点。这是一个关于如何配置它的非常好的指南,特别是本节。您可以为某些路线或所有路线配置它。

CORS设置Access-Control-Allow-Origin标头,您可以在这里了解更多信息——它只允许来自指定来源的请求。

请记住,你不需要那个包就可以实现这一点。。您可以为此构建自己的中间件。

类似于:

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://yourdomain.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

在Express文档中,它们提供了以下演示代码,您应该能够将其用作助手。

  • 客户端
  • 服务器

您可以使用带有特殊头的临时中间件。。但是,所有人所要做的就是阅读你的客户端源代码,或者查看他们浏览器中的网络选项卡,找出你正在发送的标题,这样就可以复制它们。不过,它可以防止随意的人窥探。。

const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Custom special middleware..
function blockBadHosts({ host, whitelistHeader, whitelistHeaderValue }) {
return (req, res, next) => {
if(req.headers['host'] === host) {
if(whitelistHeader && req.headers[whitelistHeader] === whitelistHeaderValue) {
next();
} else {
res.status(301).send('BAD REQUEST');
}
} else {
res.status(301).send("BAD REQUEST");
}
}
}
// Options for our custom middleware
const badHostOptions = { 
host: "localhost:3000",
whitelistHeader: "x-my-special-header", // Request must contain this header..
whitelistHeaderValue: "zoo"             // .. with this value
}
// This should succeed
app.get('/success', (req, res) => {
res.status(200).send("from /success");
});
// This should fail even if sent from Postman without correct headers
app.get('/failure', blockBadHosts(badHostOptions), (req, res) => {
res.status(200).send("from /failure");
});
// 404 route
app.use((req, res) => {
res.status(404).send("Uh oh can't find that");
})
app.listen(port, () => {
console.log(`App listening on port: '${port}'`);
});

最新更新