问题
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