clojure:未找到 class 协议方法的实现

clojure: No implementation of method of protocol found for class

我有一个环形服务器。我正在使用 Buddy 进行身份验证/授权。我通过实施伙伴协议 IAuthenticationIAuthorization-parse-authenticate-handle-unauthorized 来实施我自己的令牌后端。这是:

(ns myproject.auth
  (:require [buddy.auth.protocols :as proto]))

...

(defn my-token-backend
  ([] (my-token-backend nil))
  ([{:keys [unauthorized-handler]}]
   (reify
     proto/IAuthentication
     (-parse [_ request]
       (token-or-nil))
     (-authenticate [_ request token]
       (get-user-from-token token))
     proto/IAuthorization
     (-handle-unauthorized [_ request metadata]
       (if unauthorized-handler
         (unauthorized-handler request metadata)
         (handle-unauthorized-default request))))))

然后我在 wrap-authenticationwrap-authorization 中间件中使用我的后端:

(defn middleware [handler]
  (-> handler
      (wrap-authentication my-token-backend)
      (wrap-authorization my-token-backend)

...然后像这样使用该中间件调用我的应用程序: (def app (middleware main-routes)).

当我在浏览器中转到我的索引页面时,出现以下错误: java.lang.IllegalArgumentException: No implementation of method: :-parse of protocol: #'buddy.auth.protocols/IAuthentication found for class: myproject.auth$my_token_backend.

当我在 REPL 中调用 (reflect my-token-backend) 时,我注意到方法名称中的破折号 -parse-authenticate-handle-unauthorized 已转换为下划线.这就是我收到该错误的原因,还是错误来自其他地方?


编辑:在肖恩的评论之后,我将我的中间件更改为如下所示:

(defn middleware [handler]
  (-> handler
      (wrap-authentication (my-token-backend))
      (wrap-authorization (my-token-backend))))

class myproject.auth$my_token_backend 是函数 my-token-backend 并且您得到的错误表明对 -parse 的调用需要一个实现协议的对象 -这将是调用您的函数的结果

所以我想你想要:

(defn middleware [handler]
  (-> handler
      (wrap-authentication (my-token-backend))
      (wrap-authorization (my-token-backend)))