Cool Security Feature in MVC 1.0

If you are developing web applications, sooner or later you will come across something called Cross Site Request Forgery. The most common way to prevent CSRF attacks is by embedding additional, difficult-to-guess data fields, or tokens, in requests containing sensitive data.

Support for CSRF protection has been added to the MVC 1.0 specification. It goes like this:

First, enable CSRF Protection in your application configuration by setting the to either CsrfOptions.EXPLICIT or CsrfOptions.IMPLICIT.

public class MyApplication extends Application {

    public Map<String, Object> getProperties() {
        final Map<String, Object> map = new HashMap<>();
        // explicit CSRF Protection
        map.put(Csrf.CSRF_PROTECTION, Csrf.CsrfOptions.EXPLICIT);
        return map;

Then add the CSRF token to your forms. The Csrf object is available in Expression Language as mvc.csrf .

<form name="form" action="" method="post">
   <input type="hidden" name="${}" value="${mvc.csrf.token}"/>

If CsrfOptions.IMPLICIT is used, you’re done. All controller methods annotated with @POST and that consumes the media type x-www-form-urlencoded will be automatically checked for a valid CSRF token.

If CsrfOptions.EXPLICIT is used, then the  @CsrfValid annotation must be added exlicitly to the methods you want the CSRF token to be validated.

public Response createReservation(@BeanParam FormBean form) {
   // your controller implementation

And that’s all you need!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.