Bidi post request forbidden but get request works

I am making a get and post requests like so:

(http-cljs.client/get "someurl.com/my")

and

(http-cljs.client/post "someurl.com/my")

On the server, I have the route:

{"/my" do-something}

While do-something runs with the get request, it doesn't with the post and in the client I get 403 forbidden. In the response I get "Invalid Anti-forgery token".

These are the middleware I'm using:

(defn config []
  {:http-port  (Integer. (or (env :port) 5000))
   :middleware [[wrap-defaults site-defaults]
                wrap-with-logger
                wrap-gzip

                [wrap-reload {:dir "../../src"}]

                wrap-params
                wrap-keyword-params
                wrap-json-body
                wrap-edn-params

                ]})

When I use api-defaults however, there's no 403 forbidden, and it only happens with the site-defaults. Why is this the case?

1 answer

  • answered 2020-03-25 14:47 Jochen Bedersdorfer

    The configuration for wrap-defaults which is site-defaults will turn on the anti-forgery-middleware

    If you look at the doc string of wrap-anti-forgery you will find:

    "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 (possibly deferred) token.
      The token is also available in the request under
      `:anti-forgery-token`.
    
      By default, the token is expected to be POSTed in a form field named
      '__anti-forgery-token', or in the 'X-CSRF-Token' or 'X-XSRF-Token'
      headers.
    
      Accepts the following options:
    
      :read-token     - a function that takes a request and returns an anti-forgery
                        token, or nil if the token does not exist
    
      :error-response - the response to return if the anti-forgery token is
                        incorrect or missing
    
      :error-handler  - a handler function to call if the anti-forgery token is
                        incorrect or missing
    
      :strategy       - a strategy for creating and validating anti-forgety tokens,
                        which must satisfy the
                        ring.middleware.anti-forgery.strategy/Strategy protocol
                        (defaults to the session strategy:
                        ring.middleware.anti-forgery.session/session-strategy)
    
      Only one of :error-response, :error-handler may be specified.
    

    Anti-forgery for forms is used to prevent replay attacks. More info on CSRF attacks here: https://en.wikipedia.org/wiki/Cross-site_request_forgery