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.
Related
For my login system, I need to implement session data for different functionality when users are logged in or not.
I've only ever done sessions in flask, and google searches don't reveal a lot (or, more likely, I'm searching the wrong things). I have two questions:
Is there a canonical way to do session data in Clojure and can this specifically done in http-kit?
Is an atom enough, or would this be bad practice?
sessions will have to be managed via ring. http-kit is a server & will only use the ring spec for requests and responses.
To fetch the session
(get-in req [:session :auth-token])
To add a session to your ring response
(assoc res
:session {:auth-token auth-token
:userid (:id json-data)
:username (:username json-data)})
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've got pretty much what is in this code, at least the important parts for this question.
When I try to access some not-existing page, I don't get 404, but firstly, I get authentication dialog and I have to write credentials, to see 404. Thats not what I expect from 404 and routing. How can I overcome this issue?
Thanks a lot and Merry Xmas to all of you!
your top level lets the public paths have the first chance to supply a response, and If they don't match (or otherwise choose not to respond) then the request falls through to the part that requires authentication:
(defroutes app-routes
public-routes
(wrap-basic-authentication protected-routes authenticated?)
(route/not-found "404 Not Found"))
If, after authenticating, the route is not found then it returns a 404. Because there is no way to tell before authenticating if the private routes will claim the request all requests are falling into the wrap-basic-authentication handler. This causes the request for authentication to happen before deciding if the path is valid. It makes a lot of sense for wrap-basic-authentication not to allow an unauthenticated user to map the site by trial and error before authenticating, so it requires authentication before it will even tell you if a path exists.
In the private paths handler all the paths start with "admin" Which if it where accessible outside the protected section of the site would be a great way to know if a request like "/foo/bar/" is not private and does not exist and thus should get merit a 404 response. If you hoist the word "admin" to the top level handler and drop the wrap-basic-authentication into the private routes that should give you useful error messages without allowing unauthenticated people to map the private area of the site.
something like:
(defroutes app-routes
public-routes
(context "/admin/"
(wrap-basic-authentication protected-routes authenticated?))
(route/not-found "404 Not Found"))
Then remove the word "admin" from the start of each private path.