Security
MVC has built-in some security features to protect pages, eg. CSRF protection.
CSRF protection
MVC has built-in CSRF protection, there is a Csrf
interface.
Configure
Csrf
in theApplication
class. Override thegetProperties
method.And there are some options to configure CSRF via
Csrf.CsrfOptions
.OFF to disable Csrf.
EXPLICIT to enable Csrf with annotation
@CsrfValid
on the Controller method.IMPLICIT to enable Csrf automatically. No need
@CsrfValid
.
Add annotation
@CsrfValid
on the Controller method.In the view, add hidden field to insert the Csrf value.
When you run the codes on Glassfish, in the view, the Csrf field looks like:
Every request will generate a unique X-Requested-By value.
When the form is submitted, and it will be validated by MVC provider.
MvcContext
MvcContext
interface includes the contextual data of MVC, such as context path, application path, etc. And also includes MVC security, such as Csrf
and Encoders
.
In the above section, we have used Csrf
.
At the runtime environment, MvcContext
is exposed by EL ${mvc} in the view.
${mvc.contextPath}
will get context path.${mvc.applicationPath}
will get the application path declared in theApplication
class.${mvc.csrf.name}
generate the Csrf token name.${mvc.csrf.token}
generate the Csrf token value.${mvc.encoders.js(jsValue)}
will escape the js scripts.${mvc.encoders.html(htmlValue)}
will escape the html snippets.
Source Codes
Clone the codes from my GitHub account.
Open the mvc project in NetBeans IDE.
Run it on Glassfish.
After it is deployed and running on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.
Last updated