Hcs.Plug.Csrf

hcs · API reference

CSRF protection plug.

Implements Double Submit Cookie pattern for CSRF protection.

val generate_token : unit -> string

Extract token from cookie header

val get_header_token : header_name:string -> Server.request -> string option

Extract token from header

val get_form_token : field_name:string -> Server.request -> string option

Extract token from form body (application/x-www-form-urlencoded)

type config = {
  cookie_name : string; (* Name of CSRF cookie *)
  header_name : string; (* Name of CSRF header *)
  field_name : string; (* Name of CSRF form field *)
  secure : bool; (* Secure cookie flag *)
  same_site : [ `Strict | `Lax | `None ]; (* SameSite cookie attribute *)
}
val default_config : config
val is_safe_method : [> `GET | `HEAD | `OPTIONS | `TRACE ] -> bool

Check if method is safe (doesn't need CSRF protection)

Create Set-Cookie header value

val create : 
  ?config:config ->
  unit ->
  (Server.request -> Server.response) ->
  Server.request ->
  Server.response

Create CSRF protection plug.

For safe methods (GET, HEAD, OPTIONS, TRACE): sets CSRF cookie if not present. For unsafe methods: validates token from header or form matches cookie.

parameter config CSRF configuration