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 eitherCsrfOptions.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 xwwwformurlencoded 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!

Cool Security Feature in MVC 1.0

| Architecture & Security, Java Language| 329 views | 0 Comments
About The Author
- Ivar Grimstad is a Java Champion, JUG Leader and software architect focusing on Enterprise Java. He is participating in the Java Community Process as a member of the Expert Groups for JSR 368 (JMS 2.1), JSR 371 (MVC 1.0), JSR 375 (Java EE Security API). He is also a member of the NetBeans Dream Team. He has been working with Java since the beginning and has over the years tried out everything from lightweight mobile applications to large scale enterprise applications. His experience covers all aspects of designing architectures based on a variety of technologies including standard Java EE as well as other frameworks such as Spring and a variety of open source products. Ivar is always focusing on quality and on using the right tools and technologies for the right task to optimize the software development process. Ivar is a frequent speaker at international developer conferences.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>