public class CsrfHandler extends Object implements Route.Before
{ before(new CsrfHandler()); }
This filter require a token on POST
, PUT
, PATCH
and
DELETE
requests. A custom policy might be provided via:
setRequestFilter(Predicate)
.
Default token generator, use a UUID.randomUUID()
. A custom token generator might be
provided via: setTokenGenerator(Function)
.
Default token name is: csrf
. If you want to use a different name, just pass the name
to the CsrfHandler(String)
constructor.
The CsrfHandler
handler will read an existing token from Session
(or created a
new one is necessary) and make available as a request local variable via:
Context.attribute(String, Object)
.
If the incoming request require a token verification, it will extract the token from:
If the extracted token doesn't match the existing token (from Session
) a 403
will be thrown.
Modifier and Type | Field and Description |
---|---|
static Predicate<Context> |
DEFAULT_FILTER
Default request filter.
|
static Function<Context,String> |
DEFAULT_GENERATOR
UUID token generator.
|
Constructor and Description |
---|
CsrfHandler()
Creates a new
CsrfHandler handler and use the given name to save the token in the
Session and or extract the token from incoming requests. |
CsrfHandler(String name)
Creates a new
CsrfHandler handler and use the given name to save the token in the
Session and or extract the token from incoming requests. |
Modifier and Type | Method and Description |
---|---|
void |
apply(Context ctx)
Execute application code before next handler.
|
CsrfHandler |
setRequestFilter(Predicate<Context> filter)
Decided whenever or not an incoming request require token verification.
|
CsrfHandler |
setTokenGenerator(Function<Context,String> generator)
Set a custom token generator.
|
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
then, then
public static final Predicate<Context> DEFAULT_FILTER
public CsrfHandler(String name)
CsrfHandler
handler and use the given name to save the token in the
Session
and or extract the token from incoming requests.name
- Token's name.public CsrfHandler()
CsrfHandler
handler and use the given name to save the token in the
Session
and or extract the token from incoming requests.public void apply(@Nonnull Context ctx) throws Exception
Route.Before
apply
in interface Route.Before
ctx
- Web context.Exception
- If something goes wrong.@Nonnull public CsrfHandler setTokenGenerator(@Nonnull Function<Context,String> generator)
UUID.randomUUID()
.generator
- A custom token generator.@Nonnull public CsrfHandler setRequestFilter(@Nonnull Predicate<Context> filter)
POST
, PUT
, PATCH
and
DELETE
requests.filter
- Predicate to use.Copyright © 2020. All rights reserved.