-
Notifications
You must be signed in to change notification settings - Fork 149
Authentication and Authorization
You need to supply middleware what will authenticate and authorize.
This code uses buddy. To start, you’ll need some new middleware to apply the authentication method of your choice:
` (ns my-app.middleware (:require [buddy.auth.middleware :refer [wrap-authentication wrap-authorization]] [buddy.auth.backends.session :refer [session-backend]]))
(defn wrap-session-auth [handler] (let [backend (session-backend)] (-> handler (wrap-authentication backend) (wrap-authorization backend)))) `
In the namespace of your endpoints, you’ll need authorization rules and a check for authentication:
(:require [buddy.auth.accessrules :refer [restrict]] [buddy.auth :refer [authenticated?]] [my-app.middleware :refer [wrap-session-auth])
This is how buddy wraps access rules for a handler:
(defn wrap-restricted [handler rule] (restrict handler {:handler rule :on-error access-error}))
Then you can use restructuring to inject the new middleware:
(defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-restricted rule]))
Then, on your context/routes/endpoint, add keywords for the new middleware and the restructure-param to use it:
:middleware [wrap-session-auth] :auth-rules authenticated?
- authenticated-compojure-api - An example compojure-api app demonstrating basic and token authentication using buddy
- role-based-auth-api - An example compojure-api app demonstrating custom token authentication and role-guarded routes
- Example code as a gist: https://gist.github.com/Deraen/ef7f65d7ec26f048e2bb