单独使用 nginx 的简单 CSRF 保护 [英] Simple CSRF protection using nginx alone

查看:61
本文介绍了单独使用 nginx 的简单 CSRF 保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 nginx 服务器,提供纯 HTML 和 JS 文件.

I have an nginx server serving plain HTML and JS files.

js 代码然后调用各种 REST API 来从 API 服务器获取/发布数据.

The js code then calls various REST API to GET/POST data from API servers.

如果 nginx 收到对/api/location 的请求,它会将请求转发到另一个处理所有 API 的服务器.这个 api 服务器是用 Ruby on Rails 构建的.

If nginx receives a request for /api/ location, it forwards the request to another server which handles all the APIs. This api server is built in Ruby on Rails.

由于我所有的纯 HTML 页面都是由 nginx 直接交付的,因此在呈现它们时我无法进行服务器端会话.

Since all my plain HTML pages are delivered by nginx directly, I cant have server side sessions while they are rendered.

如何防止 CSRF 攻击?

What can I do to prevent CSRF attacks?

推荐答案

CSRF 令牌的目的是要求攻击者从您的域中读取值以发送请求.

The point of CSRF tokens is to require attackers to read a value from your domain in order to send requests.

因此,您可以在 API 中使用单独的端点,该端点仅返回 CSRF 表单令牌.

Therefore, you can have a separate endpoint in the API that simply returns a CSRF form token.

由于同源策略,攻击者将无法读取令牌(出于同样的原因,他们无法从 HTML 源读取令牌),因此您将是安全的.
这样做的缺点是需要额外的 HTTP 请求.

Attackers will not be able to read the token due to the same-origin policy (for the same reason that they can't read a token from HTML source), so you will be safe.
This has the disadvantage of requiring an extra HTTP request.

此外,请确保响应不是有效的 Javascript,否则攻击者可以将其作为

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