public class CsrfToken extends Object
A name-value pair for CSRF detection.
A CSRF token is a name-value pair that exists both as a form field and as a cookie in a POST request, so that the server can identify the request as non-CSRF.
A typical usage in html builder:
_form().method("POST").action("/addArticle").add( ... CsrfToken._input() ...
This creates a hidden <input> with a csrf token's name and value, at the same time, ensures that a cookie exists with the same name and value. When the form is submitted, the server will see that the csrf token in the form field agrees with the csrf token in the cookie.
To make sure all POST forms contain CSRF tokens, consider using a convenient builder method:
default Html5.FORM _form_post() { return Html5.html5._form() .method("POST") .enctype(FormData.ENC_MULTIPART) .add( CsrfToken._input() ); } // usage example _form_post().action("/logout").add( _button("Log Out") ); // note: even though this form contains no fields (other than the CSRF token) // the server app should still do parse(request) to detect CSRF.
Modifier and Type | Field and Description |
---|---|
static String |
DEFAULT_NAME
The default name for CSRF tokens.
|
Constructor and Description |
---|
CsrfToken()
Create a CsrfToken with the default name and the default CookieJar.
|
CsrfToken(String name,
CookieJar cookieJar)
Create a CsrfToken.
|
Instance Methods | |
---|---|
String |
name()
Name of the token.
|
String |
value()
Value of the token.
|
Html5.INPUT |
_toInput()
Build an <input> element representing this token.
|
CharSequence |
toInputString()
Make an <input> string representing this token.
|
Static Method | |
Html5.INPUT |
_input()
Build an <input> element using the default CSRF token.
|
public static final String DEFAULT_NAME
public CsrfToken()
This constructor is equivalent to
CsrfToken(CsrfToken.DEFAULT_NAME, CookieJar.current())
.
CsrfToken(String, CookieJar)
public String name()
public String value()
public Html5.INPUT _toInput()
This method is equivalent to
_input().type("hidden").name(token.name()).value(token.value());
see Html5._input()
.
This method adds an <input> to the context parent; the method name starts with underscore to be consistent with html builder methods.
You may want to cast the return value to Html4.INPUT
if you are building a strict HTML4 document.
public CharSequence toInputString()
An example return value:
<input type="hidden" name="_csrf_token" value="rMNxKwixn7hC">
public static Html5.INPUT _input()
Build an <input> element using the default CSRF token.
This method is shorthand for new CsrfToken()._toInput()
.
_toInput()