2014-06-21 33 views
0

我如何限制我的API接受&只在Rails上響應json格式&葡萄,我試過format :json在我的葡萄控制器上(例如)我可以在example.com/api/v1/ping.json上訪問它,但我也可以通過example.com/api/v1/ping.xml,example.com/api/v1/ping.foobar訪問它,並且擴展名列表繼續...如何強制Grape接受並返回僅JSON?

我會喜歡做的是,在example.com/api/v1/ping.not_json_extensions拋出錯誤

即時通訊使用:

  • 軌(4.1.1)
  • 葡萄(0.7.0)

/config/routes.rb

mount API::Base => '/api' 

/controllers/api/base.rb

module API 
class Base < Grape::API 
    mount API::V1::Base 
end 
end 

/控制器/api/v1/base.rb

module API 
module V1 
    class Base < Grape::API 
    format :json 
    mount API::V1::Ping 
    end 
end 

/controllers/api/v1/ping.rb

module API 
module V1 
    class Ping < Grape::API 
    include API::V1::Defaults 
    desc 'Returns pong.' 
    get :ping do 
     { ping: params[:pong] || 'pong' } 
    end 
    end 
end 

回答

2

看着Grape's source code,看來這是預期的行爲,但更改防止內存泄漏有效地破壞它。

您可以通過添加一個明確的檢查,以你的API類(在/controllers/api/base.rb)「手動」實現正確的行爲:

before do 
    # Make sure the format specified by the request extension is one 
    # we support 
    parts = request.path.split('.') 

    if parts.size > 1 
    extension = parts.last 

    if !extension.eql? 'json' 
     throw :error, { 
     status: 406, 
     message: "The requested format '#{extension}' is not supported." 
     } 
    end 
    end 
end 

此代碼是從葡萄的複製幾乎一字不差來源(在lib/grape/middleware/formatter.rb),並且是葡萄本身如何檢查請求中使用的擴展名。

在那個文件中,negotiate_content_type負責檢查請求的格式是否是API支持的格式,並明確給出請求擴展的優先級。然而,解析來自URI的擴展的方法format_from_extension,也會檢查格式是否受支持,如果不是,則返回nil,好像根本沒有擴展。因此,如果請求的擴展名指定了不支持的格式,則negotiate_content_type將永遠不會觸發錯誤,即使它顯然是要這樣做。

您可以通過改變formatter.rb:109代碼從

# avoid symbol memory leak on an unknown format 
return extension.to_sym if content_type_for(extension) 

簡單

return extension.to_sym 

的意見建議代碼的一個原因是這樣寫的,雖然「修理」這一點,所以繼續慎用。

+0

我看到內存泄漏,因爲攻擊者可能用大量不支持的格式向您發送垃圾郵件。因此這會不斷增加符號緩存。所以這基本上是一個內存和安全修復。對我的修復將是一個其他的投擲! – Nick

+0

事實上,它變得稍微複雜一點,因爲我改變了許多規格。看着它。 – Nick

+0

西門,我將提交一個補丁, https://github.com/realtymaps/grape/blob/v.0.9.0_format_patch/lib/grape/middleware/formatter.rb#L95-L113 https://開頭github.com/realtymaps/grape/commit/ecc245a2a2110d5051893793228cd4053929135c – Nick

相關問題