From 5cdc0a39ac1454311a3dc9cd0a8ecc38e242fdcb Mon Sep 17 00:00:00 2001 From: Maximilian Tagher Date: Fri, 29 Dec 2017 23:44:08 -0500 Subject: [PATCH] Document whitelisting certain routes to not need CSRF protection This question came up on the #yesod Slack channel and I think it's moderately common; I've seen it elsewhere. --- yesod-core/Yesod/Core/Handler.hs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/yesod-core/Yesod/Core/Handler.hs b/yesod-core/Yesod/Core/Handler.hs index 9a340803..e43ac25e 100644 --- a/yesod-core/Yesod/Core/Handler.hs +++ b/yesod-core/Yesod/Core/Handler.hs @@ -1464,6 +1464,23 @@ stripHandlerT (HandlerT f) getSub toMaster newRoute = HandlerT $ \hd -> do -- The form-based approach has the advantage of working for users with Javascript disabled, while adding the token to the headers with Javascript allows things like submitting JSON or binary data in AJAX requests. Yesod supports checking for a CSRF token in either the POST parameters of the form ('checkCsrfParamNamed'), the headers ('checkCsrfHeaderNamed'), or both options ('checkCsrfHeaderOrParam'). -- -- The easiest way to check both sources is to add the 'Yesod.Core.defaultCsrfMiddleware' to your Yesod Middleware. +-- +-- === Opting-out of CSRF checking for specific routes +-- +-- (Note: this code is generic to opting out of any Yesod middleware) +-- +-- @ +-- 'yesodMiddleware' app = do +-- maybeRoute <- 'getCurrentRoute' +-- let dontCheckCsrf = case maybeRoute of +-- Just HomeR -> True -- Don't check HomeR +-- Nothing -> True -- Don't check for 404s +-- _ -> False -- Check other routes +-- +-- 'defaultYesodMiddleware' $ 'defaultCsrfSetCookieMiddleware' $ (if dontCheckCsrf then 'id' else 'defaultCsrfCheckMiddleware') $ app +-- @ +-- +-- This can also be implemented using the 'csrfCheckMiddleware' function. -- | The default cookie name for the CSRF token ("XSRF-TOKEN"). --