似乎没有关于如何使用 Sinatra 中的 Rack::Protection 为表单启用 CSRF 保护的文档。有人做过这个吗?我似乎不知道如何告诉 Sinatra 启用此功能。
最佳答案
Sinatra 网站在这方面没有帮助,但可以按照 comments 中的描述启用 CSRF token 。在 Rack::Protection::AuthenticityToken
模块上方。
token 存储在 env['rack.session'][:csrf]
下,并且必须手动添加到名为 authenticity_token
的隐藏输入下的表单中(或者您配置它使用的任何内容)。
例如:
require 'rack/protection'
use Rack::Protection::AuthenticityToken
get '/' do
"<form method=post action=/hello>
<input type=hidden name=authenticity_token value='#{env['rack.session'][:csrf]}'>
<input type=submit>
</form>"
end
post '/hello' do
'hello' # will fail unless a valid authenticity_token parameter is passed
end
Rack::Protection::AuthenticityToken
和 Rack::Protection::FormToken
之间的区别是,如果发出请求,后者将不需要 token 通过 AJAX。
关于sinatra - 在 Sinatra 上启用 CSRF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25600046/