How can I use an anti-lock token or CSRF with the latest version of ring / compojure?

I copied some old code that worked in compojure 1.1.18 and other old libs, but using the latest versions, I cannot get it to work.

Here, my minimal sample code is copied from the minimal example here , to demonstrate that with the latest ring and compojure libraries I get an error when sending http POST even with a set of headers.

lein ring server to start it, then run

curl -X GET --cookie-jar cookies "http://localhost:3000/" , which leads to the following:

 {"csrf-token":"7JnNbzx8BNG/kAeH4bz1jDdGc7zPC4TddDyiyPGX3jmpVilhyXJ7AOjfJgeQllGthFeVS/rgG4GpkUaF"} 

But when I do it

 curl -X POST -v --cookie cookies -F " email=someone@gmail.com " --header "X-CSRF-Token: 7JnNbzx8BNG/kAeH4bz1jDdGc7zPC4TddDyiyPGX3jmpVilhyXJ7AOjfJgeQllGthFeVS/rgG4GpkUaF" http://localhost:3000/send 

I get <h1>Invalid anti-forgery token</h1>

Am I doing something wrong?

The code I borrowed was supposed to answer this question .

+7
clojure csrf-protection compojure ring
source share
1 answer

The problem was that ring-defaults (which replaces the compojure.handler namespace in compojure> = 1.2) automatically uses ring anti-forgery in normal use mode:

 (defroutes app-routes (GET "/" [] (generate-string {:csrf-token *anti-forgery-token*})) (POST "/send" [email] "ok") (resources "/") (not-found "Not Found")) (def app (-> app-routes (wrap-defaults site-defaults))) 

So, two tokens were generated for the fake, and the GET request provided an incorrect one. Removing the wrap-anti-forgery fixes the problem.

+4
source share

All Articles