Rails - RestClient未授权(401)错误,用户无法识别POST请求

时间:2014-04-04 11:35:44

标签: ruby-on-rails ruby http redmine rest-client

我正在为Redmine创建一个插件,我创建了一个方法,它发送两个HTTP请求(使用POST方法)将新文件附加到文档。

第一个请求效果很好(参见下面的Webrick控制台)

Started POST "/redmine/uploads.json?attachment_id=1&filename=testFile.txt" for <server_IP_address> at 2014-04-04 11:37:58 +0200 
Processing by AttachmentsController#upload as JSON 
Parameters: {"attachment_id"=>"1", "filename"=>"testFile.txt"} 
Current user: <user> (id=3) 
Saving attachment '/home/user/Redmine/redmine-2.4.2/files/2014/04/140404113759_testFile.txt' (72 bytes)
Rendered attachments/upload.api.rsb (1.2ms) 
Completed 201 Created in 661.6ms (Views: 82.6ms | ActiveRecord: 15.6ms)

然后执行第二个请求:

Started POST "/redmine/documents/150/add_attachment.xml" for <server_IP_address> at 2014-04-04 11:37:59 +0200 
Processing by DocumentsController#add_attachment as XML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<auth_token>", "attachments"=>{"1"=>{"filename"=>"testFile.txt", "description"=>"Dropbox blabla", "token"=>"<upToken>"}}, "commit"=>"Add", "id"=>"150"} 
Current user: anonymous 
Filter chain halted as :authorize rendered or redirected 
Completed 401 Unauthorized in 132.6ms (ActiveRecord: 3.0ms)

我收到此错误,因为此处的当前用户为anonymous(我认为),我不明白为什么,如果我在第一次请求后打印User.current,用户仍然会被记录。< / p>

我使用net/http库使用RestClient创建了第一个请求,这是我的代码:

uri = URI.parse("http://<server_IP_address>/redmine/uploads.json")

http = Net::HTTP.new(uri.host, uri.port)
file = File.new("/home/testFile.txt") 
@csrfToken = session[:_csrf_token]
@apiKey = User.current.api_key

@request = Net::HTTP::Post.new(uri.path+"?attachment_id=1&filename=testFile.txt", initheader = {'Content-Type' => "application/octet-stream", 'X-CSRF-Token' => @csrfToken, 'X-Redmine-API-Key' => @apiKey})
@request.body = @file.read
@response = http.request(@request)

@upToken = ActiveSupport::JSON.decode(@response.body)['upload']['token']

@secondResponse = RestClient.post 'http://<server_IP_address>/redmine/documents/150/add_attachment.xml', {:multipart => true, :utf8 => "\u2713", :authenticity_token => @csrfToken, :attachments => { "1" => {:filename => "testFile.txt", :description => "Dropbox blabla", :token => @upToken}}, :commit => "Add"}, 'X-Redmine-API-Key' => @apiKey, 'X-CSRF-Token' => @csrfToken, 'Cookie' => cookies[:_redmine_session]

如您所见,我尝试使用我的会话数据设置Cookie标头,但它不起作用。

我尝试使用与第一个相同的库编写第二个请求,但是我得到了同样的错误。你知道为什么我的用户不被识别吗?我怎么能改变呢?

1 个答案:

答案 0 :(得分:4)

我终于找到了为什么用户设置在anonymous

首先,我发现通过在控制器代码中添加logger.info("some text and variables"),这些信息将显示在<redmine_install_dir>/log/production.log>文件中,这非常有用。

在Redmine ApplicationController中,定义了before_filter,因此在执行第二个请求之前调用了一些方法。我看了一下这些方法,其中一个(find_current_user)将用户设置为nil,然后根据某些条件重新设置用户,我发现这些条件都没有得到验证所以用户保持nil

因此看起来问题来自Redmine API,我的action似乎未经授权。

如果有人对此感兴趣,我可以通过显示部分Redmine代码扩展我的答案(尽管你可以在GitHub或其他地方看到它)。