如何在不使用模板引擎的情况下,在API调用中使用csurf实现CSRF保护?

发布于 2025-01-19 08:36:53 字数 758 浏览 1 评论 0原文

我正在开发一个Restfull API,该API使用Express Session和Passport.js身份验证将会话存储在Connect-PG-Simple商店中。

我正在考虑使用CSURF中间件实施CSRF保护,但我没有找到任何方法。

在使用模板引擎的应用程序中,我们可以这样实现:

// CSRF
const csurf = require("csurf");
app.use(csurf());

// Register
usersRouter.get("/register", checkAuthenticated, (req, res) => {
  res.render("register", { csrfToken: req.csrfToken() });
});

// EJS
<form action="/users/register" method="POST">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
  <input type="text" id="name" placeholder="Name..." required />
  <button type="submit">Sign Up</button>
</form>

但是,如果没有这种方法,我该如何保护我的路线免受API中的CSRF攻击?

(我基本上是为我的React应用程序构建API作为后端服务器)

I'm developing a RESTfull API which uses express session and passport.js authentication to store the session in the connect-pg-simple store.

I'm looking into implementing a CSRF protection with the csurf middleware but I haven't found any way of doing it.

In an app using template engines we can implement it like this:

// CSRF
const csurf = require("csurf");
app.use(csurf());

// Register
usersRouter.get("/register", checkAuthenticated, (req, res) => {
  res.render("register", { csrfToken: req.csrfToken() });
});

// EJS
<form action="/users/register" method="POST">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
  <input type="text" id="name" placeholder="Name..." required />
  <button type="submit">Sign Up</button>
</form>

But how can I protect my routes from CSRF attacks in my API without this method?

(I'm basically building the API as a back-end server for my React application)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗心人 2025-01-26 08:36:53

将Express用作反应前端和API后端。有锅炉。这种方法的侧面好处是避免CORS,因此可以更好地安全性,因为后端无需向削弱安全性的CORS标题发送。

我基本上将API构建为我的React应用程序的后端服务器

就CSRF的实现而言,这是可以的,并且此答案适用于您的案件。唯一的区别是,答案中提到的HTML表格而不是Express在其前端服务器容量中发送的任何答案,从而使React App拨打API Endpoint(由The Files eack App)发送第二片CSRF数据(由同一Express Server),其中两种CSRF数据都附加在其上。

Use Express as both React front end and API backend. There are boilerplates for that. The side benefit of this approach is CORS avoidance and therefore better security because there is no need for the backend to send CORS headers that weaken the security.

I'm basically building the API as a back-end server for my React application

That's fine as far as CSRF implementation is concerned and this answer applies to your case. The only difference would be that instead of HTML form mentioned in the answer, you could send the second piece of CSRF data with any response sent by Express in its front end server capacity thus preparing the React app to call an API endpoint (exposed by the same Express server) with both pieces of CSRF data attached to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文