gpt4 book ai didi

ruby-on-rails - 由于protect_from_forgery,Rails 阻塞了这个请求的内容

转载 作者:行者123 更新时间:2023-12-05 01:15:18 25 4
gpt4 key购买 nike

我正在尝试使用 cURL 简单地测试我的 RESTful API。使用以下调用:

curl -d "name=jimmy" -H "Content-Type: application/x-www-form-urlencoded" http://127.0.0.1:3000/people.xml -i

然而,Rails 正在消亡:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
:8:在“同步”中

看起来它是通过一个protect_from_forgery 过滤器运行的。我认为protect_from_forgery 被排除在非HTML HTTP POST/PUT/DELETE 类型请求之外?这显然是针对 XML 格式的。

如果我传递实际的 XML 内容,它就可以工作。但我的用户将提交 POST 数据作为 URL 编码参数。我知道可以禁用protect_from_forgery 的所有各种方法,但是处理这个问题的正确方法是什么?我想保留它,这样当我有基于 HTML 的表单并处理 format.html 时,我不会忘记重新启用它。我希望用户能够向我的基于 XML 的 API 发出 HTTP POST 请求,而不会受到这种轰炸。

最佳答案

走这条路怎么样?

在您的 Controller 中:

  skip_before_filter :verify_authenticity_token, :only => :api

def api
@callback = request.body.read
if !@callback.blank?
People.create :name => @callback
end
end

在routes.rb中:
  map.api '/api', :controller => "people", :action => "api"

然后 curl :
curl -d "jimmy" http://localhost:3000/api -i

这就是我得到的:
HTTP/1.1 200 OK
Connection: close
Date: Wed, 21 Apr 2010 16:31:52 GMT
ETag: "1bafa7f069ba62f46577e0172a29b7cc"
Content-Type: text/html; charset=utf-8
X-Runtime: 141
Content-Length: 476
Set-Cookie: _tsearchtest_session=BAh7BjoPc2Vzc2lvbl9pZCIlNjJlOTViOGZhODc1NmU5NDg1MWUyYWQ3YWQ0NzFiYjU%3D--651c3bfcbb0f180c72653379678d410711ead2eb; path=/; HttpOnly
Cache-Control: private, max-age=0, must-revalidate

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>People: api</title>
<link href="/stylesheets/scaffold.css?1271863770" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>

<p style="color: green"></p>

关于ruby-on-rails - 由于protect_from_forgery,Rails 阻塞了这个请求的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2660798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com