bluemunch bluemunch - 6 months ago 11
Java Question

How can I validate my REFERER URL with glob?

I'm trying to check if my referrer String is coming from any URL with the format https://www.google.com/{{anything}}:

String referrer = req.getHeader("REFERER");

if (!(referrer.equals("https://www.google.com")) + createRegexFromGlob("*")) {
System.out.println("The referrer is valid.");
} else {
System.out.println("The referrer is not valid.");
}


Here is the glob:

public static String createRegexFromGlob(String glob)
{
String out = "^";
for(int i = 0; i < glob.length(); ++i)
{
final char c = glob.charAt(i);
switch(c)
{
case '*': out += ".*"; break;
case '?': out += '.'; break;
case '.': out += "\\."; break;
case '\\': out += "\\\\"; break;
default: out += c;
}
}
out += '$';
return out;
}


Does the referrer URL have to be a direct hit or will it automatically know if it's coming from the base URL, https://www.google.com?

I suppose I can just use
.contains
instead of making sure the string is equal to something plus a regular expression? Is there anything wrong with this?

Answer

Why not use .startsWith instead?

Try

if (referrer.startsWith("https://www.google.com"))  

Also, what on earth are are you doing with createRegexFromGlob? Simply match the URL with the following regex

^https:\/\/www\.google\.com.*$  

Java code:

String pattern = "^https:\\/\\/www\\.google\\.com.*$";
if(referrer.matches(pattern))

.contains can be used but it'll also accept URLs like

http://example.com/https://www.google.com  
Comments