Clojurescript Websockets with Sente 403 Error

312 views Asked by At

I'm attempting to setup a web socket connection from two different ports on my localhost. I'm using Sente and Immutant. I have the following, but it returns a 403 forbidden when attempting to connect

Server.clj

(defn handler
  "Comment"
  []
  "<h1>Hello World</h1>")

(let [{:keys [ch-recv send-fn connected-uids
              ajax-post-fn ajax-get-or-ws-handshake-fn]}
      (sente/make-channel-socket! (get-sch-adapter) {})]

  (def ring-ajax-post                ajax-post-fn)
  (def ring-ajax-get-or-ws-handshake ajax-get-or-ws-handshake-fn)
  (def ch-chsk                       ch-recv) ; ChannelSocket's receive channel
  (def chsk-send!                    send-fn) ; ChannelSocket's send API fn
  (def connected-uids                connected-uids) ; Watchable, read-only atom
  )

(defroutes app
  "The router."
  (GET "/" [] (handler))
  (GET  "/chsk" req (ring-ajax-get-or-ws-handshake req))
  (POST "/chsk" req (ring-ajax-post                req))
  (route/not-found
       "<h1>Page not found</h1>"))

(def my-app
  (-> app
      ;; Add necessary Ring middleware:
      ring.middleware.keyword-params/wrap-keyword-params
      ring.middleware.params/wrap-params))

(def wrapped
  (wrap-cors my-app :access-control-allow-origin [#".*"]
                       :access-control-allow-methods [:get :put :post :delete]))

(defn -main
  "Start the server"
  [& args]
  (immutant/run wrapped {:host "localhost" :port 8080 :path "/"}))

This throws no errors, and the "/" route properly displays.

Client.cljs

(let [{:keys [chsk ch-recv send-fn state]}
      (sente/make-channel-socket! "/chsk" ; Note the same path as before
      "sdasds" ; dummy
       {:type :auto ; e/o #{:auto :ajax :ws}
        :host "localhost:8080/"
       }
        )]
  (def chsk       chsk)
  (def ch-chsk    ch-recv) ; ChannelSocket's receive channel
  (def chsk-send! send-fn) ; ChannelSocket's send API fn
  (def chsk-state state)   ; Watchable, read-only atom
  )

This throws 403 errors as it tries to connect. I'm not sure why it's doing so, I've been looking at it for a while and have come up short.

1

There are 1 answers

0
Sergiy Kozachenko On

I believe this is the issue with CSRF anti-forgery:

Sente docs:

This is important. Sente has support, but you'll need to use middleware like ring-anti-forgery to generate and check CSRF codes. The ring-ajax-post handler should be covered (i.e. protected).

In Sente official example they show how to setup it properly.