Edited at

ductでbasic認証をかける

More than 1 year has passed since last update.

正直よくわかってないけど動いたからメモしておきます。


依存関係にbuddyを追加する

https://github.com/funcool/buddy-auth


project.clj

[buddy/buddy-auth "2.1.0"]



middlewareを設定する


config.edn

:duct.core/handler

{:middleware [#ig/ref :foo.auth/basic-auth]}

:foo.auth/basic-auth {}



basic認証の処理を定義する


auth.clj

(ns foo.auth

(:require [integrant.core :as ig]
[buddy.auth :refer [authenticated?]]
[buddy.auth.accessrules :refer [restrict]]
[buddy.auth.backends.httpbasic :refer [http-basic-backend]]
[buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]))

;; 入力が正しければtrueを返す関数を用意する
(defn authfn [_ {:keys [username password]}]
(and (= username "a") (= password "a")))

(def auth-backend (http-basic-backend {:authfn authfn}))

(defmethod ig/init-key ::basic-auth [_ options]
(fn [handler]
(-> handler
;; サイト全体にbasic認証をかけたいのでrestrictを使う
(restrict {:handler authenticated?})
(wrap-authorization auth-backend)
(wrap-authentication auth-backend))))