Skip to content

Instantly share code, notes, and snippets.

@coyotespike
Created July 21, 2015 18:23
Show Gist options
  • Save coyotespike/aca29bdeca1eea1e8648 to your computer and use it in GitHub Desktop.
Save coyotespike/aca29bdeca1eea1e8648 to your computer and use it in GitHub Desktop.
Getting a CSRF token from Clojure to ClojureScript
;;; Here is my hackity approach. Start with Clojure:
(ns yourapp.handler
(:require
[yourapp.homepage :refer [home-page]]
[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]))
(defroutes routes
(GET "/" [] (home-page *anti-forgery-token*)))
;;; In (ns.homepage)
(defn home-page [token]
(html
[:html
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css "css/bootstrap.min.css")
(include-css "css/flat-ui-pro.css")]
[:body
[:div#app]
[:div {:id "anti-forgery-token" :value token}]
(include-js "/js/jquery.min.js"
"https://code.jquery.com/ui/1.11.2/jquery-ui.js"
"https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"
"//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"
"/js/video.js"
"/js/flat-ui-pro.js"
"/js/flat-ui-pro.min.js"
"/js/app.js")]]))
;;;; Next, the ClojureScript side.
(ns yourapp.db
(:require
[enfocus.core :as ef]
[cljs-http.client :as http]
[dommy.core :refer-macros [sel sel1]]))
;;;; Functions to find the anti-forgery-token on the page.
(defn anti-forgery-token []
(-> :#anti-forgery-token
sel1))
(defn token []
(ef/from (anti-forgery-token) (ef/get-attr :value)))
;;;; ----------- End anti-forgery-token
;;; Include in your headers.
(defn email-us []
(http/post "/email" {:transit-params {:message "hello"}
:headers {"x-csrf-token" (token)}}))
;;;; Back on the Clojure side, Ring will automatically check that your token is the same.
;;;; The disadvantage of this approach is that it puts the token in the page body.
;;;; I believe it is meant to be in a hidden field.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment