Module io.jooby

Class CsrfHandler

java.lang.Object
io.jooby.handler.CsrfHandler
All Implemented Interfaces:
Route.Aware, Route.Before, Route.Filter

public class CsrfHandler extends Object implements Route.Before
Cross Site Request Forgery handler.
 {
   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.

Token verification

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.setAttribute(String, Object).

If the incoming request require a token verification, it will extract the token from:

  1. HTTP header
  2. HTTP cookie
  3. HTTP parameter (query or form)

If the extracted token doesn't match the existing token (from Session) a 403 will be thrown.

Since:
2.5.2
Author:
edgar
  • Field Details

    • DEFAULT_FILTER

      public static final Predicate<Context> DEFAULT_FILTER
      Default request filter. Requires an existing session and only check for POST, DELETE, PUT and PATCH methods.
    • DEFAULT_GENERATOR

      public static final Function<Context,String> DEFAULT_GENERATOR
      UUID token generator.
  • Constructor Details

    • CsrfHandler

      public 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.
      Parameters:
      name - Token's name.
    • CsrfHandler

      public 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.
  • Method Details

    • apply

      public void apply(@NonNull Context ctx) throws Exception
      Description copied from interface: Route.Before
      Execute application code before next handler.
      Specified by:
      apply in interface Route.Before
      Parameters:
      ctx - Web context.
      Throws:
      Exception - If something goes wrong.
    • setTokenGenerator

      @NonNull public CsrfHandler setTokenGenerator(@NonNull Function<Context,String> generator)
      Set a custom token generator. Default generator use: UUID.randomUUID().
      Parameters:
      generator - A custom token generator.
      Returns:
      This filter.
    • setRequestFilter

      @NonNull public CsrfHandler setRequestFilter(@NonNull Predicate<Context> filter)
      Decided whenever or not an incoming request require token verification. Default predicate requires verification on: POST, PUT, PATCH and DELETE requests.
      Parameters:
      filter - Predicate to use.
      Returns:
      This filter.