Fork me on GitHub

so I have a little tiny website that does mostly GET using compojure and ring-defaults. I made my first POST route the other day and imagine my surprise when I saw “invalid anti-forgery token” instead of my search results. I googled around but since all the libraries seem to have been in flux (aren’t they always), what is the simplest way out of my difficulty? I’m using Selmer for templating.


actsasgeek: The anti-forgery token comes from the wrap-anti-forgery middleware. It’s enabled in the site-defaults map.


It prevents CSRF attacks. You can either turn it off, if you’re not using sessions or don’t care if people outside a session can fake a POST, or you can add the *anti-forgery-token* var to a hidden field in your form.


ok, I think it’s the last part that I’m not sure how to do.


would I have to require that var and where is it required from and then just do {{*anti-forgery-token*}} in the form in the Selmer template?


In the form that you’re POSTing, you’ll want a HTML tag like: <input type=“hidden” name=“__anti-forgery-token” value=“{{*anti-forgery-token*}}”>


Where *anti-forgery-token* is ring.middleware.anti-forgery/*anti-forgery-token*


The anti-forgery middleware then checks to see if the token passed as a POST parameter matches the token in the session. This proves that the form is from your site, rather than a site an attacker has set up.


Forms predate sensible cross-origin security policies, hence the need for this.


you’re a gem. works like a charm. Thanks.


it was like having a red wire and a black wire and going, I know something goes between these two ends but ¯\(ツ)


Yeah, it’s a common problem. Hard to solve in general given that people can be using any template, though! Web development involves knowing about a lot of edge cases caused by historical artifacts.