如何验证环应用中的路由子集?

How to authenticate a subset of routes in ring application?

我有两套compojure路由,public一套,不需要认证,还有一套私有的,需要认证。

(defroutes public-routes
  (GET "/" [] homepage-handler))

(defroutes private-routes
  (GET "/secrets" [] secrets-handler))

我创建了一个中间件,它检查用户是否经过身份验证并继续中间件链或引发。

(defn wrap-must-be-authenticated [handler]
  (fn [request]
    (if (authenticated? request)
      (handler request)
      (throw-unauthorized))))

(def app
  (-> private-routes
      (wrap-must-be-authenticated)))

这很好用,所有 "private routes" 都需要身份验证。

我将如何添加 public-routes 以便它们被排除在 wrap-must-be-authenticated 之外?

我相信 defroutes returns ring handlers,所以我想我需要做类似的事情:

(-> (wrap-must-be-authenticated private-routes)
     public-routes)

一种方法是将多个 routes 定义放在包含 routes 中,并在中间件中包装 (wrap-routes) 适当的路由以限制访问:

(def all-routes
  (routes
    (-> #'private-routes
        (wrap-routes wrap-must-be-authenticated))

    #'public-routes

    (route/not-found
      (:body
        (error-page {:status 404
                     :title "page not found"})))))

我使用 buddy.auth 的 restrict:

项目的另一个示例
(defn wrap-admin [handler]
  (restrict handler {:handler (fn [req]
                                (boolean (get-in req [:session :admin?])))}))

(def app-routes
  (routes
    (-> #'admin-routes
        (wrap-routes wrap-admin)
        (wrap-routes middleware/wrap-csrf)
        (wrap-routes middleware/wrap-formats))
    (-> #'home-routes
        (wrap-routes middleware/wrap-csrf)
        (wrap-routes middleware/wrap-formats))))