如何在NodeJS中使用子域实现CSRF

时间:2020-09-14 11:40:30

标签: node.js express security cors csrf

const csrfProtection = csrf({ 
    cookie: { 
      domain: '.' + config_web.domain,
      secure: true,
      httpOnly: true,
      //sameSite: 'none'
    }, 
});

app.use(expresssession({
   store: new RedisStore({ client: redisClient }),
   secret: 'keyboard cat',
   resave: false,
   saveUninitialized: false,
   cookie: { 
     domain: '.' + config_web.domain, 
     maxAge: parseInt(cookiesTime), 
     secure: true, 
     httpOnly: true 
   }
}));

const corsOptions = {
  origin: ['https://api.domain.com', 'https://main.domain.com'],
  methods: 'POST',
  credentials: true,
  allowedHeaders: '*',//['Content-Type', 'Authorization', 'X-Requested-With'],
  optionsSuccessStatus: 200
}

app.use(cors(corsOptions));

我有主站点https://main.domain.com,将通过https://api.domain.com调用api。 分离两个子域后,api调用总是从csrf失败。我想知道我是否设置了错误的Cookie内容?

1 个答案:

答案 0 :(得分:-1)

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

刚发现在前端添加xhrFields即可工作