CSRF token with Selmer, Ring

2018 05 29 No Comments

Firstly install Selmer and Ring. Here are my project.clj

(defproject test "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :min-lein-version "2.0.0"
  :resource-paths ["public" "resources" "templates"]
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [compojure "1.5.1"]
                 [ring/ring-defaults "0.2.1"]
                 [mysql/mysql-connector-java "5.1.32"]
                 [yesql "0.5.3"]
                 [selmer "1.11.7"]
                 [org.clojure/tools.namespace "0.2.11"]
                 [proto-repl "0.3.1"]
                 [proto-repl-charts "0.3.1"]

  :plugins [[lein-ring "0.12.4"]]
  :ring {:handler test.handler/app}
  {:dev {:dependencies [[javax.servlet/servlet-api "2.5"]
                        [ring/ring-mock "0.3.0"]]}})

After that, create crsf-token as tag to use in selmer template engine.

(add-tag! :csrf-token (fn [args context-map] (anti-forgery-field)))

Here are routes

; rou

(defroutes app-routes
  (GET "/" []
    (render-file "index.html" {}))
  (POST "/deneme-post" req (deneme req))
  (route/not-found "Not Found"))

(def app
  (wrap-defaults app-routes site-defaults))

In Index.html you use to put csrf hidden input: {% csrf-token %}

<form class="test" method="post" onsubmit="return false">
  {% csrf-token %}
  <input type="text" name="deneme_input" value="">
  <button type="submit">gönder</button>

Some jquery:

$(function() {
  $("form").submit(function() {
    var data = $(this).serialize()
    $.post("/deneme-post", data, function(res) {

And our deneme function to response post

(defn deneme [req] ( str "posted successfully" ))

You can find the working project on github. It is login/register example but includes csrf also.

Regards 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *