Invalid anti-forgery token

2.2k views Asked by At

I'm getting an "Invalid anti-forgery token" when I try using POST method in a Clojure Webapp project I created using Compojure template.

I researched, and Ring middle ware creates CSRF (cross site request forms) tokens to authenticated requests coming from other sites (to use someone else's credentials who has already logged in and access pages not allowed to access).

These tokens are default, and we need to use ring.middleware 's wrap-params around our WebApp. Couldn't get anywhere much. Please HELP !! How to get rid of Invalid anti-forgery token.

My handler.clj file is :

(ns jsonparser-webapp.handler
   (:require [compojure.core :refer :all]
        [compojure.route :as route]
        [jsonparser-webapp.views :as views])
   (:use [ring.middleware.params :only [wrap-params]])

(defroutes app-routes
  (GET "/" 
    [] 
    (views/home-page))
  (GET "/goto" 
    [] 
    (views/goto))
  (POST "/posted"
     {params :params} 
     (views/posted params))
  (route/not-found "Not Found"))

(def app
    (wrap-params app-routes site-defaults))

My views.clj file is

(ns jsonparser-webapp.views
   (:require [hiccup.page :as hic-p]
             [hiccup.form :as hf]))

(defn gen-page-head
  [title]
  [:head
     [:title title]])

(defn home-page
  []
  (hic-p/html5
      (gen-page-head "Json Parser Home.")
      [:h1 "Welcome."]
      [:p "Json Web App."]
      [:a {:href "http://localhost:3000/goto"} "Goto"]
      [:p (hf/form {:action "/posted" :method "POST"} 
             (hf/text-field "TextInput")    
             (hf/submit-button "Submit"))]))

(defn goto
  []
  (hic-p/html5
      (gen-page-head "Goto Page.")
      [:h1 "Hi."]
      [:p "Go where?"]))

(defn posted
   [{:keys [x]}]
   (hic-p/html5
      (gen-page-head "Posted.")
      [:h1 "You posted."]
      [:p x]))

Project created using Compojure template of Clojure in Eclipse CounterClockwise.

1

There are 1 answers

0
Bram On BEST ANSWER

You have to add (anti-forgery-field) to your form, so that the anti forgery token is injected into the POST params.

Like this:

(ns jsonparser-webapp.views
  (:require [hiccup.page :as hic-p]
>           [ring.util.anti-forgery :refer [anti-forgery-field]]
            [hiccup.form :as hf]))

(defn gen-page-head
  [title]
  [:head
   [:title title]])

(defn home-page
  []
  (hic-p/html5
    (gen-page-head "Json Parser Home.")
    [:h1 "Welcome."]
    [:p "Json Web App."]
    [:a {:href "http://localhost:3000/goto"} "Goto"]
    [:p (hf/form {:action "/posted" :method "POST"} 
         (hf/text-field "TextInput")    
 >       (anti-forgery-field)
         (hf/submit-button "Submit"))]))