Skip to content

Instantly share code, notes, and snippets.

@Noia
Created November 10, 2011 10:51
Show Gist options
  • Save Noia/1354591 to your computer and use it in GitHub Desktop.
Save Noia/1354591 to your computer and use it in GitHub Desktop.
web.xml definition & related java
<filter>
<filter-name>XFrameOptionsHeaderFilter</filter-name>
<filter-class>no.emily.web.security.XFrameOptionsHeaderFilter</filter-class>
<init-param>
<param-name>option</param-name>
<param-value>sameorigin</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>XFrameOptionsHeaderFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
package no.emily.web.security;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
/**
* @author Emily Soldal
* @created 10. nov. 2011
*/
public class XFrameOptionsHeaderFilter implements Filter {
private FilterConfig filterConfig = null;
private Options state = null;
enum Options {
allow, deny, sameorigin;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
String initParameter = this.filterConfig.getInitParameter("option");
state = find(initParameter);
this.filterConfig.getServletContext().log(String.format("Initialized %s with parameter %s", getClass().getSimpleName(), state));
}
private Options find(String initParameter) {
if (initParameter != null) {
// We don't want to use Enum.valueOf because that throws a relatively meaningless exception.
for (Options o : Options.values()) {
if (o.name().equalsIgnoreCase(initParameter)) {
return o;
}
}
}
throw new IllegalArgumentException("Required option parameter missing or invalid. Valid values: allow, deny, sameorigin");
}
public void destroy() {
this.filterConfig = null;
state = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.addHeader("X-Frame-Options", state.name());
chain.doFilter(request, response);
}
}
@Noia
Copy link
Author

Noia commented Nov 10, 2011

Hmm, on review, the ALLOW option is supposed to allow for an origin. It shouldn't be hard to add though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment