How to validate URIs by checking if those refer to a given domain name?

倾然丶 夕夏残阳落幕 提交于 2020-01-06 09:09:50

问题


I am running Ruby on Rails 4.1.1 and I would like to validate URIs by checking if those are within a given domain name. That is, a uri string can be sent as params to my controller and I would like to check if that uri "refers" to my application domain name www.myapp.com. Of course, the uri should be a valid URI reference.

# Invalid URIs
www.website.com
http://www.website.com
http://www.website.com/
https://www.website.com/
ftp://www.website.com/
ftps://www.website.com/
http://www.website.com/some/path

# Valid URIs
www.myapp.com
http://www.myapp.com
http://www.myapp.com/
https://www.myapp.com/
ftp://www.myapp.com/
ftps://www.myapp.com/
http://www.myapp.com/some/path

How can I make that (maybe by using just Ruby on Rails)?

Note: I am validating URIs in order to allow users to set custom redirects and I am aware of vulnerabilities. I plan to run validations in a method stated in my application_controller.rb.


回答1:


require 'uri'

uri = URI.parse 'http://www.website.com/some/path'

isOK = case uri.host
       when 'www.website.com' then true
       else false
       end

#⇒ true

Hope it helps.




回答2:


Currently Addressable is my preferred choice for working with URIs:

require 'addressable/uri'

Addressable::URI.parse('http://www.myapp.com/some/path').host == 'www.myapp.com'


来源:https://stackoverflow.com/questions/27859332/how-to-validate-uris-by-checking-if-those-refer-to-a-given-domain-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!