2016-01-29 289 views
3

當我在使用Compojure模板創建的Clojure Webapp項目中嘗試使用POST方法時,我收到「無效的防僞令牌」。無效的防僞令牌

我研究了一下,Ring中間件創建了CSRF(跨站請求表單)令牌給來自其他站點的身份驗證請求(使用其他站點的用戶憑據已經登錄並訪問不允許訪問的頁面)。

這些令牌是默認的,我們需要使用ring.middleware的總結PARAMS圍繞我們的Web應用程序。無法獲得任何東西。請幫忙 !!如何擺脫無效的防僞標記的。

我handler.clj文件是:

(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)) 

我views.clj文件是使用Clojure中的模板的Compojure在Eclipse中創建逆時針方向

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

項目。

回答

2

您必須添加(anti-forgery-field)到您的形式,從而使防僞造令牌注入post數據。

像這樣:

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