Invalid anti-forgery token

时光总嘲笑我的痴心妄想 提交于 2021-02-07 13:35:40

问题


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:


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"))]))


来源:https://stackoverflow.com/questions/35085348/invalid-anti-forgery-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!