如何使用Csurf保护我的React App API? [英] How to secure my react app api with csurf?

查看:127
本文介绍了如何使用Csurf保护我的React App API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的React应用中添加csrf保护,但是我一直都收到错误的令牌

I am trying to add csrf protection to my react app but I am getting an error Invalid token all the time

import bodyParser from 'body-parser';
import cookieSession from 'cookie-session';
import passport from 'passport';
import csrf from 'csurf'
import config from '../../config'
import AuthRoutes from "./routes/AuthRoutes";

/* Test only */
import cookieParser from 'cookie-parser';


const session = cookieSession({
    maxAge:24 * 60 * 60 * 1000,
    keys:[config.COOKIE_KEY],
    name:'authentication',

});



export default app => {

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(session);
    app.use(passport.initialize());
    app.use(passport.session());

    /* Test */
    app.use(cookieParser());
    app.use(csrf({ cookie: true }));

    app.use(function (err, req, res, next) {
        if (err.code !== 'EBADCSRFTOKEN') return next(err)

        // handle CSRF token errors here
        res.status(403)
        res.send('form tampered with')
    })

    /*Passport Config*/
    require('../../services');

    /* Register, Login these are routes i want to protect */
    AuthRoutes(app);

}


推荐答案

您需要要:

1.在服务器上配置 csrf 库。这样可以确保该库将发送附加到服务器响应的第一条数据。

2.在服务器上使用 csrf 库生成第二条数据数据并将其附加到服务器响应(例如,发送给客户端的HTML表单)。完成此步骤后,服务器响应将携带两段CSRF数据。

3.在客户端上,获取第二段数据并将其插入到您要发送的请求中(例如,表单您将要提交)。

You need to:
1. Configure csrf library on the server. This ensures the library will send the first piece of data attached to the server responses.
2. Use csrf library on the server to generate the second piece of data and attach it to the server response (e.g. HTML form sent to the client). After this step is completed the server response will carry two pieces of CSRF data.
3. On the client take the second piece of data and insert it into the request you are about to send (e.g. the form you are about to submit).

步骤1

到目前为止,仅步骤(1)已完成。您要求 csrf 库将第一个数据作为cookie发送。您可以使用更好的配置:

Step 1
So far only the step (1) has been completed. You asked the csrf library to send the first piece of data as a cookie. You could have used a better configuration:

app.use(csrf({cookie: {
    httpOnly: true,
}}));

它可确保浏览器不允许客户端上的任何JS触摸其中的第一条数据cookie是好的,因为没有合法的理由让任何脚本知道此cookie中的内容。稍后,在生产中以及使用HTTPS时,可以选择将 secure:true 添加到上述配置中,以使服务器拒绝通过不安全的连接发送此cookie。 。

It ensures the browser won't allow any JS on the client to touch the first piece of data inside the cookie which is good because there is no legit reason for any script to know what is inside this cookie. Later on, in production and when you use HTTPS, you can optionally add secure: true to the above configuration to make the server refuse to send this cookie over connections that are not secure.

第2步

要获取第二条数据,请调用 csrfToken() csrf 中间件为方便起见在 Request 对象中添加了另一个属性,因此可以这样调用: const secondPiece = req.csrfToken()。您可以按照自己喜欢的任何方式将第二个数据放入服务器响应中:放入另一个具有任意名称的cookie(除了 _csrf 名称已经被步骤1 Cookie)或放入您喜欢的HTTP标头中。

Step 2
To get the second piece of data call csrfToken(). The csrf middleware added another property to Request object for your convenience so it can be called like this: const secondPiece = req.csrfToken(). You can put the second piece of data into the server responce in any way or manner you like: into another cookie with an arbitrary name (except for the _csrf name already taken by the step 1 cookie) or into HTTP header named as you like.

例如,以下代码会将其放入另一个Cookie中:

For example this code will put it into another cookie:

res.cookie('XSRF-TOKEN', req.csrfToken());

第3步

在客户端上写JS获取第二条数据并将其放入预定义的位置/位置之一(在要发送到服务器的请求内),其中 csrf 中间件默认情况下会搜索

这篇关于如何使用Csurf保护我的React App API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆