如何将Friend auth添加到Chestnut模板

时间:2015-03-25 20:22:37

标签: authentication clojure middleware ring compojure

我已经努力了几天试图简单地使用安全库Friend来使用Chestnut clj / cljs模板。

POST uri的/login请求应该登录并允许访问受保护的路由,例如/role-user。但由于某些原因我无法登录,POST返回303并将我回到根页面。

我在http-handler函数中添加了Friend中间件。这是应用此类中间件的正确位置吗?我想也许重装或api-defaults中间件可能搞乱朋友中间件?但是,删除它们并不能解决问题。

(def http-handler
  (if is-dev?
    (-> #'routes
        (reload/wrap-reload)
        (friend/authenticate
          {:allow-anon? true
           :login-uri "/login"
           :default-landing-uri "/"
           :unauthorized-handler #(-> (h/html5 [:h2 "You do not have sufficient privileges to access " (:uri %)])
                                      resp/response
                                      (resp/status 401))
           :credential-fn (fn [x]
                            (let [res (creds/bcrypt-credential-fn @users x)]
                              (log/info x)
                              (log/info res)
                              res))
           :workflows [(workflows/interactive-form)]})
        (wrap-defaults api-defaults))
    (wrap-defaults routes api-defaults)))

基于print语句,我能够确定在POST请求中使用正确的参数调用了credential-fn函数,并且该函数返回正确的(经过身份验证的)结果。

http-handler用作

(defn run-web-server [& [port]]
  (let [port (Integer. (or port (env :port) 10555))]
    (print "Starting web server on port" port ".\n")
    (run-jetty http-handler {:port port :join? false})))

(defn run-auto-reload [& [port]]
  (auto-reload *ns*)
  (start-figwheel))

(defn run [& [port]]
  (when is-dev?
    (run-auto-reload))
  (run-web-server port))

对于它的价值,这是我的路线。

(defroutes routes
  (GET "/" req
    (h/html5
      misc/pretty-head
      (misc/pretty-body
       (misc/github-link req)
       [:h3 "Current Status " [:small "(this will change when you log in/out)"]]
       [:p (if-let [identity (friend/identity req)]
             (apply str "Logged in, with these roles: "
               (-> identity friend/current-authentication :roles))
             "anonymous user")]
       login-form
       [:h3 "Authorization demos"]
       [:ul
        [:li (e/link-to (misc/context-uri req "role-user") "Requires the `user` role")]]
       [:p (e/link-to (misc/context-uri req "logout") "Click here to log out") "."])))
  (GET "/login" req
    (h/html5 misc/pretty-head (misc/pretty-body login-form)))
  (GET "/logout" req
    (friend/logout* (resp/redirect (str (:context req) "/"))))
  (GET "/role-user" req
    (friend/authorize #{::users/user} "You're a user!")))

1 个答案:

答案 0 :(得分:1)

我明白了。 (wrap api-defaults)不允许会话,而且Friend正在尝试使用它们。我应该使用site-defaults代替。有关详细信息,请参阅ring middleware