如何安全地将Redux存储从服务器传递到客户端

时间:2022-08-24 14:52:25

I am working on a React app with server-side rendering. The app uses Redux for state management and Redux Saga for async actions. In pseudocode, what I am doing on the server side right now is:

我正在使用服务器端渲染的React应用程序。该应用程序使用Redux进行状态管理,使用Redux Saga进行异步操作。在伪代码中,我现在在服务器端做的是:

1) initialize Redux store and run Redux saga on it
2) wait until all necessary data is fetched
3) render React component to string
4) send rendered React component to the client
   (along with the populated store for rehydration on the client side)

My problem is with step 4. Right now, I am passing the rendered React component and the store to an ejs view that looks roughly like this:

我的问题在于第4步。现在,我将渲染的React组件和商店传递给ejs视图,看起来大致如下:

<html>
    <head>
        <meta charset="utf-8">
        <title>Test</title>
        <link rel="stylesheet" type="text/css" href="/styles.css">
        <script>
            var __data = <%-JSON.stringify(store) %>;
        </script>
    </head>
    <body>

        <main><%- app %></main>

        <script type="text/javascript" src="/vendor.js"></script>
        <script type="text/javascript" src="/bundle.js"></script>
    </body>
</html>

(in the code above, app is the rendered React component, and store is the Redux store)

(在上面的代码中,app是呈现的React组件,store是Redux商店)

Trouble is, the above code, specifically

麻烦的是,上面的代码,特别是

<script>
    var __data = <%-JSON.stringify(store) %>;
</script>

does not escape html, so if my store contains a string with the <script> tag, it will be valid html, and opens the app to XSS attacks.

不会转义html,所以如果我的商店包含带有

If instead of <%- %> use <%= %> like so: var __data = "<%= JSON.stringify(store) %>";, I get a string that is invalid JSON:

如果代替<% - %>使用<%=%>,如下所示:var __data =“<%= JSON.stringify(store)%>”;,我得到一个无效的JSON字符串:

"{&#34;greetingReducer&#34;:{&#34;message&#34;:&#34;Hello world!&#34;} etc.

which I am not sure how to transform back to valid JSON.

我不知道如何转换回有效的JSON。

So my question (silly as it may seem) is: what’s a proper way of passing a Redux store (HTML-escaped string of a JSON object) in the HTML template to the client and how to transform that string back to a JavaScript object on the client.

所以我的问题(看起来很愚蠢)是:将HTML模板中的Redux存储(HTML转义的JSON对象字符串)传递给客户端以及如何将该字符串转换回JavaScript对象的正确方法是什么?客户端。

1 个解决方案

#1


4  

You can try serialize-javascript if you're ok with including another module to do this. It has support to escape harmful HTML strings.

你可以尝试序列化-javascript,如果你可以包括另一个模块来做到这一点。它支持逃避有害的HTML字符串。

#1


4  

You can try serialize-javascript if you're ok with including another module to do this. It has support to escape harmful HTML strings.

你可以尝试序列化-javascript,如果你可以包括另一个模块来做到这一点。它支持逃避有害的HTML字符串。