ring

hawari 2018-03-26T08:29:06.000310Z

How can I apply a middleware only on certain route? For example GET /userinfo will need to authenticate a user first, whereas GET /somethingelse won't require an access token at all.

hawari 2018-03-26T08:31:13.000216Z

Is path + method matching on the middleware is the way to go here?

ikitommi 2018-03-26T09:24:35.000114Z

@hawari.rahman17 many routing libs support this out-of-the-box, some samples: Compojure-api (macros):

(context "/api" []
  :middleware [wrap-api]
  (GET "/userinfo" []
    :middleware [wrap-auth]
    (ok ...))
  (GET "/somethingelse" []
    (ok ...)))
Reitit (data):
["/api" {:middleware [wrap-api]}
 ["/userinfo" {:get {:middleware [wrap-require-auth]
                     :handler ...}}]
 ["/somethingelse" {:get ...}]]

hawari 2018-03-26T09:32:14.000538Z

@ikitommi I've found that routes in compojure is quite extendable, I ended up doing something like this:

(def restricted-routes
  (-> (routes (GET "/protected-path" [] protected-fn))
      (wrap-routes authorize)))

(defroutes app-routes
  (GET "/unprotected-routes" [] "Hello")
  restricted-routes)

ikitommi 2018-03-26T09:33:19.000407Z

I think you don’t need the routes within the restricted-routes.

hawari 2018-03-26T09:33:21.000012Z

My problem is sometimes in the same context, there exists a route that doesn't need to be authorized first

ikitommi 2018-03-26T09:34:49.000056Z

yes, but that’s to way to do it with Compojure. Compojure-api just adds sugar for it, e.g. the :middleware key.

ikitommi 2018-03-26T09:35:02.000481Z

oh, then, yes.

ikitommi 2018-03-26T09:36:14.000379Z

if you are using nginx-clojure, you should be carefull with wrap-routes. It uses mutable request maps and the wrap-routes doesn’t work with it.

hawari 2018-03-26T09:38:21.000348Z

I mean, I'm not using nginx-clojure but I'd like to know what I'd signed up for with wrap-routes

ikitommi 2018-03-26T09:42:05.000342Z

e.g. wrap-routes adds “call me if the path matches” info to the request. As the request is mutable, the info is still present in the request for the next routes. Next route will see that and invoke the mw. Kinda fatal.

hawari 2018-03-26T09:47:48.000168Z

So in other words, even if the path matches the routes not listed in restricted-routes, the middleware authorize will still gets invoked?

hawari 2018-03-26T09:48:12.000296Z

Wow, thanks for the warning @ikitommi, I'll be sure to remember that

ikitommi 2018-03-26T09:55:50.000433Z

yes, it gets called for the next route by Compojure. np.