ring

Ovi Stoica 2024-10-29T11:00:27.554549Z

This might not be the best place to ask, and if so, please point me to the correct channel. Mocking anti-forgery-token : I have a full stack app that renders web pages and has a JSON API. I have https://github.com/ring-clojure/ring-anti-forgery added. My app is managed through integrant. This means I have an app component, the ring app’s handler. I’m trying to test the API like this:

(require '[ring.mock.request :as mock]
           '[ring.middleware.anti-forgery :refer [*anti-forgery-token*]]
           '[integrant.repl.state :as state]
           '[saas.util :as utils]
           '[ring.middleware.anti-forgery :as anti-forgery])

  (def mock-sign-up-req (-> (mock/request :post "/api/account/sign-up")
                            (mock/header :content-type "application/json")
                            (mock/header "X-CSRF-TOKEN" (force *anti-forgery-token*))
                            (mock/json-body (random-account))))


  (def app (-> state/system :handler/ring))

  (app mock-sign-up-req) ;; => 403 Invalid anti-forgery token
How could I mock the anti-forgery-token to do testing?

Ovi Stoica 2024-10-29T11:11:45.485669Z

Aditional info: • My app uses cookie sessions

2024-10-29T14:32:43.664399Z

i think you can implement a mock strategy to do this

2024-10-29T14:32:57.073559Z

: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)
from the wrap-anti-forgery docs

🚀 1
2024-10-29T14:35:07.187119Z

and then you can call (make-app ... {:anti-forgery-strategy (mock-strategy)}) and pass in the anti-forgery-strategy to your app

Ovi Stoica 2024-10-29T16:22:59.338949Z

Yes, I think this is the way! Thank you!

👍 1