Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Transform incident management with machine learning and analytics to help you maintain optimal performance and availability while keeping pace with the growing demands of digital business with this eBook, brought to you in partnership with BMC.

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.

@ApplicationPath("mvc")
public class MyApplication extends Application {

    @Override
    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}"/>
</form>

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.

@CsrfValid
@POST
@Path("new")
public Response createReservation(@BeanParam FormBean form) {
   // your controller implementation
}

And that’s all you need!

Evolve your approach to Application Performance Monitoring by adopting five best practices that are outlined and explored in this e-book, brought to you in partnership with BMC.

Topics:
security ,csrf

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}