如何保护React单页应用程序/创建React应用程序

时间:2019-02-08 23:54:21

标签: javascript node.js reactjs csrf

我正在使用React Single Page App / Creat React App建立一个电子商务网站,并在我的后端Iam中使用Express.js建立一个电子商务网站。

因为对服务器的每个请求都使用API​​,这很危险吗? 因为每个人都可以访问我们的API吗?

那么您如何处理呢?

我应该使用CSRF吗?

我已经用此CSRF搜索了几天的方法,结果保持不变,不起作用!

我已经使用CSURF Express进行了尝试,但遇到了很多错误。大多数人通过CSRF令牌将其发送给客户端进行交谈。我尝试过,当第一页打开时有时出现错误Invalid CSRF token

Server.js

import express from 'express';
import bodyParser from 'body-parser';
import passport from 'passport';
import connection from './config/conn';
import { 
    CategoryRoutes,
    ProductRoutes,
    CartRoutes,
    AuthRoutes,
    TrackRoutes,
    AddressRoutes,
    ShippingRoutes,
    UIRoutes,
    LookbookRoutes,
    CheckoutRoutes
} from './modules';
import session  from 'express-session';
import csrf  from 'csurf'
import cors from 'cors'
import cookieParser  from 'cookie-parser'
// import cookieSession from 'cookie-session'
import passportSetup from './config/passport-setup';
import keys from './config/keys';
import uuidv4  from 'uuid/v4';
import UAparser  from 'ua-parser-js';
import { ensureSession } from './config/sessionCheck';
// import path from 'path';
const app = express();

app.use(session({
    genid: function (req) {
        return uuidv4() // use UUIDs for session IDs
    },
    name:keys.session.name,
    secret: keys.session.secret,
    resave: false,
    saveUninitialized: true,
    rolling:true,
    cookie: { 
        secure: false,
        httpOnly: true,
        maxAge:keys.session.maxAge, // satu hari,
        sameSite:true,
     }

}));

// app.use('/public',express.static(path.join(__dirname,'public')));

app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser());
app.use(csrf({ cookie: false }));

app.disable('x-powered-by');
app.use((req,res,next)=>{
    res.header('X-XSS-Protection', '1; mode=block');
    res.header('X-Frame-Options','deny');
    res.header('X-Content-Type-Options','nosniff');
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.cookie('csrf_token', req.csrfToken(), { maxAge: 3600, sameSite: true })
    next(); 
})

app.use(cors({ origin: keys.origin.url }))

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', function (req, res, next) {

    var ua = UAparser(req.headers['user-agent']);
    res.end(JSON.stringify(ua, null, '  '));
})
app.use('/api/', ensureSession, [
    CategoryRoutes, 
    ProductRoutes, 
    CartRoutes, 
    AuthRoutes, 
    TrackRoutes, 
    AddressRoutes, 
    ShippingRoutes, 
    UIRoutes,
    LookbookRoutes,
    CheckoutRoutes
]);

const port = process.env.PORT || 5000;
app.listen(port, (err) => {
    if(err){
        console.log(err);
    }else{
        console.log(`Server running on port ! ${port}`);
    }

});

使用Redux从客户端

export const fetchCartList = (value)=>disbatch=>{
    console.log(Cookies.get())
    disbatch(loadingCart());
    axios({
        method: 'POST',
        url: '/api/v1/track/cart',
        headers: { "x-csrf-token": Cookies.get("csrt_token") }
    }).then(res => {
        let dataType = typeof res.data.cart_list;
        if(typeof res.data.token_c !== "undefined"){
            localStorage.setItem("hammerstout_c", res.data.token_c);
        }
        if(dataType !== "undefined"){
        disbatch({
            type:FETCH_CART_LIST,
            payload:res.data.cart_list
        })
        }else{
            disbatch(stopLoadingCart());
            localStorage.removeItem("hammerstout_c");
        }


    }).catch(err => {
        disbatch({
            type: GET_ERRORS,
            payload: err.response.data
        });
        if (err.response.data.error) {
            disbatch(stopLoadingCart());
        }
    })
}

结果

有时候我会遇到这样的错误:

CSRF未定义:

CSRF IS UNDEFINED

在第一个请求中,我设置了Cookie: CSRF SET

request list

有时会成功: 如您所见CSRF令牌已设置: TOKEN HAS BEEN SET CSRF SET SUCCESS

我发现大部分是React服务器端渲染,而不是客户端渲染。

那么如何保护React Single Page App / Creat React App?

请给我一个使用Express和React SPA处理此CSRF的示例或教程

我尝试了几天,结果仍然不起作用:(

0 个答案:

没有答案