Last active
April 25, 2018 23:31
-
-
Save bjpeterdelacruz/ca36e25602b87f433d0446ae76f2419b to your computer and use it in GitHub Desktop.
How to sanitize a URL to prevent open redirection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bjpeter.sampleapp.utils; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URLEncoder; | |
import org.apache.commons.lang3.StringUtils; | |
public WebUtils() { | |
private WebUtils() { | |
} | |
public static String safeReturnUri(String uri, boolean encode) { | |
String appUrl = "http://www.bjpeter.com"; /* read in secure application URL from properties file */ | |
if (StringUtils.isEmpty(uri)) { | |
return safeParam(appUrl, encode); | |
} | |
String tempUri = uri; | |
// Return URLs cannot point outside of application. Let's add http or https here | |
// so we can handle all URLs as an absolute URL. | |
if (!uri.startsWith("http://") && !uri.startsWith("https://")) { | |
tempUri = appUrl.substring(0, appUrl.lastIndexOf('/')) + uri; | |
} | |
if (tempUri.startsWith(appUrl)) { | |
return safeParam(tempUri, encode); | |
} | |
return safeParam(appUrl, encode); | |
} | |
public static String safeParam(String param, boolean encode) { | |
String parameter = stripTags(param); | |
if (!encode) { | |
return stripParens(parameter); | |
} | |
try { | |
return URLEncoder.encode(parameter, "UTF-8"); | |
} | |
catch (UnsupportedEncodingException e) { | |
return parameter; | |
} | |
} | |
public static String stripTags(String uri) { | |
return StringUtils.replace(StringUtils.replace(uri, "<", ""), ">", ""); | |
} | |
public static String stripParens(String uri) { | |
return StringUtils.replace(StringUtils.replace(uri, "(", ""), ")", ""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment