Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Last active April 25, 2018 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjpeterdelacruz/ca36e25602b87f433d0446ae76f2419b to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/ca36e25602b87f433d0446ae76f2419b to your computer and use it in GitHub Desktop.
How to sanitize a URL to prevent open redirection
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