MVC has built-in some security features to protect pages, eg. CSRF protection. html
MVC has built-in CSRF protection, there is aCsrfinterface. git
ConfigureCsrfin theApplicationclass. Override thegetPropertiesmethod. github
@Override public Map<String, Object> getProperties() { Map<String, Object> props = new HashMap<>(); props.put(Csrf.CSRF_PROTECTION, Csrf.CsrfOptions.EXPLICIT); //view folder //props.put(ViewEngine.DEFAULT_VIEW_FOLDER, ViewEngine.VIEW_FOLDER); return super.getProperties(); }
And there are some options to configure CSRF viaCsrf.CsrfOptions. mvc
Add annotation@CsrfValidon the Controller method. app
@POST @CsrfValid @ValidateOnExecution(type = ExecutableType.NONE) public Response save(@Valid @BeanParam TaskForm form) { }
In the view, add hidden field to insert the Csrf value. ide
<input type="hidden" name="${mvc.csrf.name}" value="${mvc.csrf.token}"/>
When you run the codes on Glassfish, in the view, the Csrf field looks like: ui
<input value="f3ca389f-efba-4f28-afe7-2a1e7231a238" name="X-Requested-By" type="hidden" />
Every request will generate a unique X-Requested-By value. spa
When the form is submitted, and it will be validated by MVC provider. code
MvcContextinterface includes the contextual data of MVC, such as context path, application path, etc. And also includes MVC security, such asCsrfandEncoders. orm
In the above section, we have usedCsrf.
At the runtime environment,MvcContextis exposed by EL ${mvc} in the view.
Clone the codes from my github.com account.
Open the mvc project in NetBeans IDE.