Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top