Skip to content

Instantly share code, notes, and snippets.

@sandipchitale
Last active August 6, 2023 00:26
Show Gist options
  • Save sandipchitale/357bd201ba3ebe295c8725d79091ab66 to your computer and use it in GitHub Desktop.
Save sandipchitale/357bd201ba3ebe295c8725d79091ab66 to your computer and use it in GitHub Desktop.
Base Controller #springboot
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
/**
* This controller returns the JavaScript code to set the <base href="/server.contextPath"/>.
*/
@Configuration
@RestController
class BaseController {
// Logger
private static final Logger LOG = LoggerFactory.getLogger(BaseController.class);
private final Environment environment;
private final ServletContext servletContext;
BaseController(Environment environment, ServletContext servletContext) {
this.environment = environment;
this.servletContext = servletContext;
}
@GetMapping(value = "/base", produces = { "text/javascript" })
public String contextPath(HttpServletRequest request) {
// This header is set by the load balancer proxy
String xForwardedServer = request.getHeader("x-forwarded-server");
// header must be set by the load balancer proxy if the context path at LB is not /
String xForwardedPrefix = request.getHeader("x-forwarded-prefix");
// If it is set we should not consider our own context path
String contextPath = servletContext.getContextPath();
if (xForwardedServer != null) {
contextPath = xForwardedPrefix == null ? "" : xForwardedPrefix;
}
contextPath = simpleSanitize(contextPath);
contextPath = contextPath + "/";
return "(function () {\n"
+ " var head = document.getElementsByTagName('head').item(0);\n"
+ " var base = document.createElement('base');\n" + " base.href = '" + contextPath + "';\n"
+ " head.appendChild(base);\n" + "})();\n";
}
// IA-11973 - Very simple sanitizer for now. At some point we should try to leverage
// some other library to do more sophisticated sanitization/validation. I do not know enough
// about the context path here and want to avoid breaking it for valid characters.
private static String simpleSanitize(String input) {
if (Objects.isNull(input) || input.length() == 0) {
return input;
}
return input.replaceAll("(?i)<script.*?>.*?</script.*?>", "")
.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment