【问题标题】:Invalid anti-forgery token无效的防伪令牌
【发布时间】:2016-05-07 05:41:23
【问题描述】:

我在使用 Compojure 模板创建的 Clojure Webapp 项目中尝试使用 POST 方法时收到“无效的防伪令牌”。

我研究过,Ring 中间件会为来自其他站点的经过身份验证的请求创建 CSRF(跨站点请求表单)令牌(以使用已登录的其他人的凭据并访问不允许访问的页面)。

这些标记是默认的,我们需要在 WebApp 周围使用 ring.middleware 的 wrap-params。无法到达任何地方。请帮忙 !!如何摆脱无效的防伪令牌

我的 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文件是

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

在 Eclipse CounterClockwise 中使用 Clojure 的 Compojure 模板创建的项目。

【问题讨论】:

    标签: eclipse clojure compojure ring counterclockwise


    【解决方案1】:

    您必须将(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"))]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 2017-07-21
      • 2021-06-09
      • 2023-03-30
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多