Fork me on GitHub
#ring
<
2016-07-29
>
actsasgeek20:07:38

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.

weavejester20:07:08

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

weavejester20:07:07

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.

actsasgeek20:07:36

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

actsasgeek20:07:43

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?

weavejester20:07:22

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*}}”>

weavejester20:07:05

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

weavejester20:07:43

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.

weavejester20:07:03

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

actsasgeek20:07:16

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

actsasgeek21:07:28

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

weavejester21:07:19

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.