Last active
December 19, 2015 07:19
-
-
Save lillesand/5917603 to your computer and use it in GitHub Desktop.
Jersey sin Csrf protection
This file contains hidden or 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
/** | |
* | |
* Også kan jeg kommentere her. | |
* | |
* Simple server-side request filter that implements CSRF protection as per the | |
* <a href="http://www.nsa.gov/ia/_files/support/guidelines_implementation_rest.pdf">Guidelines for Implementation of REST</a> | |
* by NSA (section IV.F) and | |
* section 4.3 of <a href="http://seclab.stanford.edu/websec/csrf/csrf.pdf">this paper</a>. | |
* If you add it to the request filters of your application, it will check for X-Requested-By header in each | |
* request except for those that don't change state (GET, OPTIONS, HEAD). If the header is not found, | |
* it returns {@link Status#BAD_REQUEST} response back to the client. | |
* | |
* @author Martin Matula | |
*/ | |
public class CsrfProtectionFilter implements ContainerRequestFilter { | |
private static final Set<String> METHODS_TO_IGNORE; | |
private static final String HEADER_NAME = "X-Requested-By"; | |
static { | |
HashSet<String> mti = new HashSet<String>(); | |
mti.add("GET"); | |
mti.add("OPTIONS"); | |
mti.add("HEAD"); | |
METHODS_TO_IGNORE = Collections.unmodifiableSet(mti); | |
} | |
@Override | |
public ContainerRequest filter(ContainerRequest request) { | |
if (!METHODS_TO_IGNORE.contains(request.getMethod()) && !request.getRequestHeaders().containsKey(HEADER_NAME)) { | |
throw new WebApplicationException(Status.BAD_REQUEST); | |
} | |
return request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment