ring

aratare 2021-02-05T11:14:56.027300Z

Hi there. I have a question regarding how to use the ring anti forgery middleware. As I understand the middleware is used to check if the request has the CSRF header, but how would one set it up in the first place? Currently I'm sending a new token back to the clientside via response header, which the client will pull it out and put it in subsequent requests. But so far all I have is Invalid anti-forgery token. I suspect this has something to do with *anti-forgery-token* but not quite sure how to set it up properly. Would appreciate any insight. Thanks in advance.

jumar 2021-02-06T13:28:25.029Z

The docs say it:

(defn wrap-anti-forgery
  "Middleware that prevents CSRF attacks. Any POST request to the handler
  returned by this function must contain a valid anti-forgery token, or else an
  access-denied response is returned.

  The anti-forgery token can be placed into a HTML page via the
  *anti-forgery-token* var, which is bound to a random key unique to the
  current session. By default, the token is expected to be in a form field
  named '__anti-forgery-token', or in the 'X-CSRF-Token' or 'X-XSRF-Token'
  headers.
That is the *anti-forgerky-token* var should be set by ring and you should use the var to pass the value to the http response, save it on client and then pass it back to the server when you're doing the POST request. E.g. we use Selmer so we pass this as a html template param:
:csrf-token *anti-forgery-token*
This is used by javascript functions like this:
<script>
  (() => {
    abc.init({
...
      csrfToken: '{{csrf-token}}'
    });
and we also use the convenient anti-forgery-field function and add the csrf token automatically to all html templates
(selmer.parser/add-tag! :csrf-field (fn [_ _] (anti-forgery-field)))

aratare 2021-02-06T15:14:13.029200Z

will give it a try thanks. Somehow the last time I was using *anti-forgery-token* it was empty.