Over a million developers have joined DZone.

Cool Security Feature in MVC 1.0

DZone's Guide to

Cool Security Feature in MVC 1.0

New in MVC 1.0 is Cross Site Request Forgery protection support! Here's how to enable CSRF protection.

· Performance Zone ·
Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

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 thejavax.mvc.security.CsrfProtection 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="${mvc.csrf.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!

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

security ,csrf

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}