I am creating a simple API which returns JSON data back to the user. For development purposes, I would like to enable CORS so that my react frontend can call the API locally. For the moment, it complains
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access.
Question: How can I use ring-cors (or something similar) to enable CORS and send back JSON data?
Observations: With the current (app ..), (wrap-cors ...) provides no cross origin header.
I have tried several variations of the order but none seem to work. For instance, (wrap cors ...) followed by (wrap-defaults ...) doesn't work.
MWE
(ns qitab-api.handler
(:require [compojure.core :refer :all]
[compojure.route :as route]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.middleware.cors :refer [wrap-cors]]
[ring.util.response :as r]))
(defroutes app-routes
(GET "/" []
(r/response {:hello "World!!"}))
(route/not-found "Not Found"))
(def app
(-> app-routes
wrap-json-body
wrap-json-response
(wrap-defaults site-defaults)
(wrap-cors :access-control-allow-origin [#".*"] :access-control-allow-
headers [:get])))
P.S. I have looked at several other questions which relate to CORS and Compojure however, none of them deal with the JSON aspect.
:access-control-allow-headers should be :access-control-allow-methods. Then it should work.
Related
I have a ring webapp that uses noir.session as follows:
(def app (-> app-routes
(session/wrap-noir-session)
(wrap-defaults site-defaults))) ; both from ring.middleware.defaults
However, it seems like session variables are lost between the requests. The server keeps sending a Set-Cookie header even though the client provides the Cookie header.
Using trial and error, I found out that when I disable ring's anti-forgery wrapper as follows, the same session lives across requests:
(def app (-> app-routes
(session/wrap-noir-session)
(wrap-defaults (assoc-in site-defaults [:security :anti-forgery] false))))
but of course I don't want that. Why is this, and how can I fix my problem without risking CSRF attacks?
Browsing the source code of all involved middleware, I found out that lib-noir's wrap-noir-session re-implements parts of ring's wrap-session. That lead me to the following experiment:
(def app (-> app-routes
(session/wrap-noir-session {:store (memory-store)})
(wrap-defaults (assoc site-defaults :session false))))
Here as well, sessions live across requests.
Here's the culprit: wrap-defaults already applies wrap-session, so when the wrap-noir-session handler is listed as well, wrap-session is actually invoked twice.
The final solution couldn't be simpler: Use wrap-noir-session* instead. According to the docs, it "expects that wrap-session has already been used." It seems that the contrary is true for wrap-noir-session.
(def app (-> app-routes
(session/wrap-noir-session*)
(wrap-defaults site-defaults)))
Hopefully, this will save you some time.
I have a web app which has CSRF protection but I need to disable this protection for some endpoints(public APIs) so I can send Rest calls without having problem.
Here is my code:
(def handler (-> route.all/routes
log-middleware
(wrap-defaults site-defaults);;which provides CSRF protection
wrap-exceptions
wrap-reload
wrap-gzip))
(defn start
[port]
(jetty/run-jetty handler {:port port}))
P.S: I use Liberator along with Ring
Thanks to James Reeves, he has answered this question over here
(Note, I'm using Reagent, Secretary, and Compojure (among others))
I want to create a route /sectest/:id, and if I point my browser to that route, I get the following error:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3449/sectest/css/site.css".
asdf:1
Refused to execute script from 'http://localhost:3449/sectest/js/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
But if I click on a link in the browser that navigates to that route, it works fine...
Here's the pertinent code:
Client Side:
(secretary/defroute "/sectest/:id" [id]
(do
(js/console.log (str "Hi " id))
(session/put! :current-page #'my-page)))
Server Side:
(defroutes routes
(GET "*" [] loading-page) ;this anticipates client-side routing only
(GET "/cards" [] cards-page)
(resources "/")
(not-found "Not Found"))
(def app (wrap-middleware #'routes))
So the following link takes me to my-page, and the console prints "Hi asdf" just fine:
[:div [:a {:href "/sectest/asdf"} "SECTEST"]]
But if I type in http://localhost:3449/sectest/asdf, I get an error, and I can't seem to trace it. I suspect it might have something to do with the code trying to find resources located at /sectest, (which it shouldn't), but I can't confirm this or figure out how to work with it... I am new to clojure, so forgive if I'm massively ignorant on some point, any thoughts?
Take a look at your server side routing, effectively you only have one route:
(GET "*" [] loading-page)
As it handles everything all following routes will never trigger. Order matters:
(defroutes routes
(GET "/cards" [] cards-page)
(resources "/")
(GET "*" [] loading-page) ;this anticipates client-side routing only
)
The above should do the trick, I removed the 404 route, as this should be handled by the frontend routing.
The reason it currently works when clicking on a page link in your SPA is that it will get handled by secretary. If you enter the url manually you are doing a page reload and the request is handled by compojure initially.
Edit:
After taking a closer look, relative links to your css/js files in your html template are most likely the culprit here:
/sectest/js/app.js
The compojure resources route won't match and the default catch all route loading-page is served as css/js file to your browser. Hence the error.
For my dev env I also had to correct the :asset-path of my boot cljs task as the source mapping files suffered from the problem. Should be similiar with lein-figwheel.
I copied some old code that was working in compojure 1.1.18 and other old libs, but using the latest versions I can't get it to work.
Here's my minimal example code copied from the minimal example here to demonstrate that with latest ring and compojure libraries, I get an error when I send an http POST, even with the header set.
lein ring server to start it, then do
curl -X GET --cookie-jar cookies "http://localhost:3000/" which results in something like this:
{"csrf-token":"7JnNbzx8BNG/kAeH4bz1jDdGc7zPC4TddDyiyPGX3jmpVilhyXJ7AOjfJgeQllGthFeVS/rgG4GpkUaF"}
But when I do this
curl -X POST -v --cookie cookies -F "email=someone#gmail.com" --header "X-CSRF-Token: 7JnNbzx8BNG/kAeH4bz1jDdGc7zPC4TddDyiyPGX3jmpVilhyXJ7AOjfJgeQllGthFeVS/rgG4GpkUaF" http://localhost:3000/send
I get <h1>Invalid anti-forgery token</h1>
Am I doing something wrong?
The code I borrowed was intended to answer this question.
The problem was that ring-defaults (which replaces the compojure.handler namespace in compojure >= 1.2) automatically uses ring anti-forgery in the usual mode of use:
(defroutes app-routes
(GET "/" [] (generate-string {:csrf-token
*anti-forgery-token*}))
(POST "/send" [email] "ok")
(resources "/")
(not-found "Not Found"))
(def app
(-> app-routes
(wrap-defaults site-defaults)))
So two anti-forgery tokens were being generated and the GET request provided the invalid one. Removing the wrap-anti-forgery line fixed the problem.
I'm having trouble with my Clojure server middlewares. My app has the following requirements:
Some routes should be accessible with no problems. Others require basic authentication, so I'd like to have an authentication function that sits in front of all the handler functions and makes sure the request is verified. I've been using the ring-basic-authentication handler for this, especially the instructions on how to separate your public and private routes.
However, I'd also like the params sent in the Authorization: header to be available in the route controller. For this I've been using Compojure's site function in compojure.handler, which puts variables in the :params dictionary of the request (see for example Missing form parameters in Compojure POST request)
However I can't seem to get both 401 authorization and the parameters to work at the same time. If I try this:
; this is a stripped down sample case:
(defn authenticated?
"authenticate the request"
[service-name token]
(:valid (model/valid-service-and-token service-name token)))
(defroutes token-routes
(POST "/api/:service-name/phone" request (add-phone request)))
(defroutes public-routes
controller/routes
; match anything in the static dir at resources/public
(route/resources "/"))
(defroutes authviasms-handler
public-routes
(auth/wrap-basic-authentication
controller/token-routes authenticated?))
;handler is compojure.handler
(def application (handler/site authviasms-handler))
(defn start [port]
(ring/run-jetty (var application) {:port (or port 8000) :join? false}))
the authorization variables are accessible in the authenticated? function, but not in the routes.
Obviously, this isn't a very general example, but I feel like I'm really spinning my wheels and just making changes at random to the middleware order and hoping things work. I'd appreciate some help both for my specific example, and learning more about how to wrap middlewares to make things execute correctly.
Thanks,
Kevin
AFAIK, ring.middleware.basic-authentication doesn't read anything from the :params in request and ring.core.request/site doesn't put anything authentication-related there either.
But in any ring handler, you can still access the headers. Something like:
(GET "/hello"
{params :params headers :headers}
(str "your authentication is " (headers "authentication")
" and you provided " params))
Similarly, you can use that to write your own middleware to put authentication-related stuff in params, if you really want to.