Search code examples
webclojureluminus

anti forgery token error when calling a clojure function in luminus


I am learning clojure with luiminus and I am trying to parse arguments following an example. By using curl I am sending username and password to be printed calling foo in the following route. However, I get the "Invalid anti-forgery token error". And I have looked for solutions but can't find any. Note that I am using the wrap middleware line also. Any suggestions?

curl --header "Content-Type: application/json" --request POST --data '{"username":"xyz","password":"xyz"}' 'localhost:3000/foo/bar?foo=bar'

home.clj:

(ns wkom.routes.home
  (:require
   [wkom.layout :as layout]
   [wkom.db.core :as db]
   [clojure.java.io :as io]
   [wkom.middleware :as middleware]
   [ring.util.response]
   [ring.util.http-response :as response]))

(defn home-page [request]
  (layout/render request "home.html" {:docs (-> "docs/docs.md" io/resource slurp)}))

(defn about-page [request]
  (layout/render request "about.html"))

(defn bootstrap [request]
  (layout/render request "bootstrap.html"))

(defn form [request]
  (layout/render request "form.html"))

(defn foo2 [{:keys [path-params query-params body-params]}]
  (print "from foo2\n")
  {:status 200 :body (str "path params: " path-params "\nquery params: " query-params "\nbody params: " body-params)})

(defn home-routes []
  [ "" 
   {:middleware [middleware/wrap-csrf
                 middleware/wrap-formats]}
   ["/foo/:bar" {:post (fn [{:keys [path-params query-params body-params]}]
                {:status 200 :body   (str "path params: " path-params
                                      "\nquery params: " query-params
                                      "\nbody params: " body-params)})}]
   ["/" {:get home-page}]
   ["/about" {:get about-page}]
   ["/bootstrap" {:get bootstrap}]
   ["/form" {:get form
             :post foo2}]
   ["/foo2/:bar" {:post foo2}]])

Solution

  • The default project's home.html sets the token and can be accessed from cljs as js/csrfToken. It should be included in post requests as :x-csrf-token.

    Unless you use another method of forgery prevention, it is inadvisable to comment out the middleware.