如何在特定的启动路由上应用环网防伪?

时间:2018-10-27 13:08:30

标签: clojure ring

在包装用metosin/reitit reitit.ring/ring-router创建的特定路由时,我不断收到“无效的防伪令牌”。我也尝试过reitit的middleware registry,但是也没有用。尽管我可以用wrap-sessionwrap-anti-forgery包装整个处理程序,但这使reitt在允许使用特定于路由的中间件方面的优势丧失了。

(ns t.core

 (:require [immutant.web :as web]
           [reitit.ring :as ring]
           [ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
           [ring.middleware.content-type :refer [wrap-content-type]]
           [ring.middleware.params :refer [wrap-params]]
           [ring.middleware.keyword-params :refer [wrap-keyword-params]]
           [ring.middleware.session :refer [wrap-session]]
           [ring.util.anti-forgery :refer [anti-forgery-field]]
           [ring.util.response :as res]))


(defn render-index [_req]
 (res/response (str "<form action='/sign-in' method='post'>"
                    (anti-forgery-field)
                    "<button>Sign In</button></form>")))

(defn sign-in [{:keys [params session]}]
 (println "params: " params
          "session:" session)
 (res/redirect "/index.html"))

(defn wrap-af [handler]
 (-> handler
     wrap-anti-forgery
     wrap-session
     wrap-keyword-params
     wrap-params))

(def app
 (ring/ring-handler
  (ring/router [["/index.html" {:get render-index
                                :middleware [[wrap-content-type]
                                             [wrap-af]]}]
                ["/sign-in"    {:post sign-in
                                :middleware [wrap-af]}]])))

(defn -main [& args]
 (web/run app {:host "localhost" :port 7777}))

1 个答案:

答案 0 :(得分:0)

事实证明,metosin/reitit为每个路由创建一个会话存储(有关更多信息,请参考issue 205);换句话说,环防伪不起作用,因为reitt不在每个路由上使用相同的会话存储。

在回答此问题时,维护者提出了以下建议(从该问题中复制以方便在Stack Overflow中引用):

  1. 将包装会话安装在路由器外部,这样整个应用程序只有一个mw实例。环形处理程序中有:middleware选项:
(require '[reitit.ring :as ring])
(require '[ring.middleware.session :as session])

(defn handler [{session :session}]
  (let [counter (inc (:counter session 0))]
    {:status 200
     :body {:counter counter}
     :session {:counter counter}}))

(def app
  (ring/ring-handler
    (ring/router
      ["/api"
       ["/ping" handler]
       ["/pong" handler]])
    (ring/create-default-handler)
    ;; the middleware on ring-handler runs before routing
    {:middleware [session/wrap-session]}))
  1. 创建一个会话存储并在路由表中使用它(会话中间件的所有实例将共享该存储)。
(require '[ring.middleware.session.memory :as memory])

;; single instance
(def store (memory/memory-store))

;; inside, with shared store
(def app
  (ring/ring-handler
    (ring/router
      ["/api"
       {:middleware [[session/wrap-session {:store store}]]}
       ["/ping" handler]
       ["/pong" handler]])))

此答案中未显示的是维护人员要求进行PR的第三个选项。