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}
  :profiles
  {: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.
(more…)

Using Kemal CSRF handler with Crinja

2018 05 19 No Comments

I assume that you are using kemal, kemal-session and kemal-csrf. Require them and use add_handler to handle requests.

Default input name is authenticity_token so I used it.

require "kemal"
require "kemal-session"
require "kemal-csrf"

add_handler CSRF.new(
  allowed_methods: ["GET", "HEAD", "OPTIONS", "TRACE"],
  error: ->myerrorhandler(HTTP::Server::Context)
)

def myerrorhandler(env)
  if env.request.headers["Content-Type"]? == "application/json"
    {"error" => "csrf error"}.to_json
  else
    "No token!"
  end
end

Kemal.run

Create a function to use it in templates
(more…)