Skip to content

Instantly share code, notes, and snippets.

@skazhy
Created January 10, 2018 08:01
Show Gist options
  • Save skazhy/51e0cd083a9067985796bf4c76c90303 to your computer and use it in GitHub Desktop.
Save skazhy/51e0cd083a9067985796bf4c76c90303 to your computer and use it in GitHub Desktop.
anti_forgery_async.clj
(defn wrap-anti-forgery
"Middleware that prevents CSRF attacks. Any POST request to the handler
returned by this function must contain a valid anti-forgery token, or else an
access-denied response is returned.
The anti-forgery token can be placed into a HTML page via the
*anti-forgery-token* var, which is bound to a random key unique to the
current session. By default, the token is expected to be in a form field
named '__anti-forgery-token', or in the 'X-CSRF-Token' or 'X-XSRF-Token'
headers.
Accepts the following options:
:read-token - a function that takes a request and returns an anti-forgery
token, or nil if the token does not exist
:error-response - the response to return if the anti-forgery token is
incorrect or missing
:error-handler - a handler function to call if the anti-forgery token is
incorrect or missing.
Only one of :error-response, :error-handler may be specified."
([handler]
(wrap-anti-forgery handler {}))
([handler options]
{:pre [(not (and (:error-response options) (:error-handler options)))]}
(let [read-token (:read-token options default-request-token)
error-handler (make-error-handler options)]
(fn
([request]
(go-try
(let [token (find-or-create-token request)]
(binding [*anti-forgery-token* token]
(if (valid-request? request read-token)
(add-session-token (<? (handler request)) request token)
(error-handler request))))))
([request respond raise]
(go-try
(let [token (find-or-create-token request)]
(binding [*anti-forgery-token* token]
(if (valid-request? request read-token)
(<? (handler request #(respond (add-session-token % request token)) raise))
(error-handler request respond raise))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment