Ruby OpenURI 允许从 https 到 http 的重定向。

huangapple go评论57阅读模式
英文:

Ruby OpenURI allow redirections from https to http

问题

Ruby的open-uri库会在从https到http的重定向时[阻止重定向](https://github.com/ruby/open-uri/blob/343464b0a419ea33fb1461471297501a4ae9d2fa/lib/open-uri.rb#L226),并显示错误信息:

>RuntimeError (重定向被禁止:https://link -> http://link)

有没有办法修改这种行为以允许这些重定向?当然,猴子补丁`OpenURI.redirectable?`似乎是一个明显的选项,但我宁愿避免这样做。在这里还有其他选择吗?大多数现有的答案建议使用[open_uri_redirections](https://github.com/open-uri-redirections/open_uri_redirections),但这个宝石已经不再维护,也不能正常工作。
英文:

The Ruby open-uri library blocks redirections from https to http with the error

>RuntimeError (redirection forbidden: https://link -> http://link)

Is there any way to modify this behavior to allow these redirects? Of course monkey patching OpenURI.redirectable? seems an obvious option but I'd prefer to avoid this if possible. Are there any other options here? Most existing answers suggest open_uri_redirections but this gem is unmaintained and no longer works.

答案1

得分: 1

open_uri_redirections gem 并没有特殊处理,只是以一种糟糕的有状态方式对 OpenURI.redirectable? 进行了猴子补丁。

如果不涉及安全考虑(即你不发送 cookies/referer),只需重写它。

def OpenURI.redirectable?(uri1, uri2)
  uri1.scheme.downcase == uri2.scheme.downcase ||
  (/\A(?:https?|ftp)\z/i =~ uri1.scheme && /\A(?:https?|ftp)\z/i =~ uri2.scheme)
end

这个函数唯一的变化是在 2.4 版本时允许 http 到 https 的重定向,因此我们可以认为它非常稳定。

但确实,考虑使用更全功能的 HTTP 客户端。

英文:

open_uri_redirections gem does nothing special but monkey patching OpenURI.redirectable? in an ugly stateful way.

If the security consideration doesn't apply (i.e. you don't send cookies/referer) - just rewrite it.

def OpenURI.redirectable?(uri1, uri2)
  uri1.scheme.downcase == uri2.scheme.downcase ||
  (/\A(?:https?|ftp)\z/i =~ uri1.scheme && /\A(?:https?|ftp)\z/i =~ uri2.scheme)
end

The only change for this function was in time of 2.4 allowing http->https, so we can assume this is very stable.

But indeed, consider more full-featured http-client instead

huangapple
  • 本文由 发表于 2023年2月24日 08:25:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定