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

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

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!

Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:
security ,csrf

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}