Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.