I'm not really understanding https://github.com/clojure-liberator/liberator and the list of decision points that it provides to the developer. How would one implement a basic auth/auth service using/alongside/on-top-of the library?
The idiomatic way is to implement the :authorized? decision point. However there is currently no support for the handling of basic or digest authentication. A practical approach is to use ring-basic-authentication for authentication and handle only authorization in the resource. The following example uses ring-basic-authentication and sets the token to a users's role. This role is then checked by liberator in authorized?
(defresource admin-only
:handle-ok "secrect"
:handle-unauthorized "for admins only"
:authorized? (fn [{{token :token} :request}]
(= "admin" token)))
;; token returned encodes role
(defn authenticated? [name pass]
(cond (and (= name "scott")
(= pass "tiger")) "admin")
(and (= name "jack")
(= pass "jill")) "user)))
(def app (wrap-basic-authentication admin-only authenticated?))
from the readme"
Resources are compatible with Ring and can be wrapped in Ring middleware. When evaluated, a resource returns a function which takes a Ring request and returns a Ring response.
so you can then wrap it in ring-basic-authentication
(use 'ring.middleware.basic-authentication)
(defn authenticated? [name pass] (and (= name "foo") (= pass "bar")))
(def app (-> routes .. (wrap-basic-authentication authenticated?))
Related
I have an endpoint called /account which provides user info(returns html).
When unauthorised user tries to access this endpoint I need to be able to redirect to login page but in Liberator I found post-redirect so far and it is just for post methods.
I need to redirect get methods as well, how can I achieve this?
I found a workaround following code does the trick:
(defn account
[]
(resource :allowed-methods [:get]
:available-media-types ["text/html"]
:exists? (fn [_] false)
:existed? (fn [_] true)
:moved-temporarily? (fn [ctx] {:location "/redirected-path-or-url"})
:handle-ok (fn [ctx]
[:html ...])
:handle-exception (fn [_]
"Something went wrong")))
Or you can check :authorized? and return login html from :handle-unauthorized but I doubt it about it's a good practice or not.
I'm trying to access basic session data in a ring middleware to, in my case, copy user data into the request for easier access.
(def app
(->
(handler/site app-routes)
(wrap-user-auth) ; <--- my middleware
(session/wrap-session {:store (cookie-store {:key "something super secret"})})))
Middleware:
(defn wrap-user-auth [handler]
(fn [request]
(println request )
(let [user (get (request :session) :user nil)]
(let [response
(handler
(if-not (nil? user)
(assoc request :user user :is_authenticated? true)
(assoc request :user nil :is_authenticated? false)))]
response
))))
Session data is always empty when printing request, even though it has been set and is accessible through the views. I tried messing around with middleware order but can't figure out why the atom is empty.
Some random route where session data is available
(ANY "/foo" request (println (request :session)))
Found a solution.
Turns out this problem is 'somewhat' related to Compojure/Ring: Why doesn't a session with cookie-store survive a server restart?, which explains that 2 session middleware are being used: One by compojure, one by wrap-session. After changing both middleware to the same storage engine, the atom is filled with my session data - although I don't quite understand why.
I am putting this as an answer rather than a comment since it solves the actual problem. Happy to hear why this is happening though!
I'm using the ring basic-authentication library available for compojure. The authenticated? function takes a username and a password in order to authenticate, but in my particular case I need to access other parameters passed in by the user request besides a username and a password.
For instance, consider a case where there are multiple servers, and a user has an account on a particular server. That user would therefore need to authenticate with (log-on to) a particular server. Therefore I need his username, password, AND server to do the authentication.
Handling a "normal" case which just calls for a username and password might look something like this (using example sql to hit a database):
; curl my_id:my_pass#localhost/my_request
(defn authenticated? [id password]
(first (select user (where {:id id :password password}) (limit 1))))
I'd like to do something like this:
; curl my_id:my_pass#localhost/my_server/my_request
(defn authenticated? [id password ??server??]
(first (select user (where {:server server :id id :password password}) (limit 1))))
I guess my question is, how do I access all request params from inside authenticated? Or, alternatively, how do I pass the server id into the authenticated? function?
Thanks.
In accordance with the comments to the question above, the approach would look like this (just a sketch, I haven't tested whether this works due to lack of a running setup with ring):
(defn wrap-basic-auth-server [handler authfn]
(fn [request]
(-> request
(wrap-basic-authentication (partial authfn (get-in request [:params :server])))
handler)))
What's happening here is that the code is assuming that your server url param will have been added by wrap-params (from ring.middleware.params) to the request map. wrap-basic-authentication is called then with the handler (typical ring middleware, i.e. any other wrapper / handler coming afterwards) and a new (partial) function, which is just your authenticate function which has already swallowed the server arg.
And then instead of just calling wrap-basic-authentication in your routes, you need to add wrap-params and wrap-basic-auth-server and you need your new auth function. E.g.
(defn authenticated? [server user pass]
... your code ...)
(def app
(-> app-routes
... potential other wrappers elided ...
(wrap-params)
(wrap-basic-auth-server authenticated?)))
As I said, I've not tested this code, but it should get you started.
I am writing a web API using Compojure with basic-authentication middleware. The basic authentication part looks something like:
(defn authenticated? [id pass]
(and (= id "blah")
(= pass "blah"))
id and pass are passed in using the id:pass#website technique. My problem is, I would like to access this id and pass further on down where the routes are processed with the various GET, PUT, POST, etc. headings. But I can't figure out how to do this, and haven't had any luck googling around.
; i'd like to access id and pass here
(defroutes routes
(GET "/" [] {:status 200 :headers {} :body "hi!"})
...)
I presume the solution is for the above to somehow "add" id and pass to some set of variables that can be accessed where the routes are processed, but I have no idea how to add nor to access them.
Hopefully someone can point me in the right direction - thanks.
Assuming you are talking about https://github.com/remvee/ring-basic-authentication, the authenticated? fn can return a truthly value that will be added to the request in the :basic-authentication. Something like (untested):
(defn authenticated? [id pass]
(and (= id "gal")
(= pass "foo")
{:user id :passwd pass}))
(defroutes routes
(GET "/" {the-user :basic-authentication} {:status 200 :headers {} :body (str "hi! Mr. " (:user the-user) " your password is " (:passwd the-user))})
...)
The return of the authenticated? method is associated in request map referenced by the key :basic-authentication. Here goes an example with a route that returns the user. You could, however, return a map or any other object and access it through :basic-authentication key.
(defn authenticated? [user password] user)
(defroutes require-auth-routes
(GET "/return-user" request (.toString (:basic-authentication request)))
(def my-app
(routes
(-> require-auth-routes
(wrap-basic-authentication authenticated?)))
I'm currently writing an API in Clojure using Compojure (and Ring and associated middleware).
I'm trying to apply different authentication code depending on the route. Consider the following code:
(defroutes public-routes
(GET "/public-endpoint" [] ("PUBLIC ENDPOINT")))
(defroutes user-routes
(GET "/user-endpoint1" [] ("USER ENDPOINT 1"))
(GET "/user-endpoint2" [] ("USER ENDPOINT 1")))
(defroutes admin-routes
(GET "/admin-endpoint" [] ("ADMIN ENDPOINT")))
(def app
(handler/api
(routes
public-routes
(-> user-routes
(wrap-basic-authentication user-auth?)))))
(-> admin-routes
(wrap-basic-authentication admin-auth?)))))
This doesn't work as expected because wrap-basic-authentication indeed wraps routes so it gets tried regardless of the wrapped routes. Specifically, if the requests needs to be routed to admin-routes, user-auth? will still be tried (and fail).
I resorted to use context to root some routes under a common base
path but it's quite a constraint (the code below may not work it's simply to illustrate the idea):
(defroutes user-routes
(GET "-endpoint1" [] ("USER ENDPOINT 1"))
(GET "-endpoint2" [] ("USER ENDPOINT 1")))
(defroutes admin-routes
(GET "-endpoint" [] ("ADMIN ENDPOINT")))
(def app
(handler/api
(routes
public-routes
(context "/user" []
(-> user-routes
(wrap-basic-authentication user-auth?)))
(context "/admin" []
(-> admin-routes
(wrap-basic-authentication admin-auth?))))))
I'm wondering if I'm missing something or if there's any way at all to achieve what I want without constraint on my defroutes and without using a common base path (as ideally, there would be none).
(defroutes user-routes*
(GET "-endpoint1" [] ("USER ENDPOINT 1"))
(GET "-endpoint2" [] ("USER ENDPOINT 1")))
(def user-routes
(-> #'user-routes*
(wrap-basic-authentication user-auth?)))
(defroutes admin-routes*
(GET "-endpoint" [] ("ADMIN ENDPOINT")))
(def admin-routes
(-> #'admin-routes*
(wrap-basic-authentication admin-auth?)))
(defroutes main-routes
(ANY "*" [] admin-routes)
(ANY "*" [] user-routes)
This will run the incoming request first through admin-routes and then through user routes, applying the correct authentication in both cases. The main idea here is that your authentication function should return nil if the route is not accessible to the caller instead of throwing an error. This way admin-routes will return nil if a) the route actually does not match defined admin-routes or b) the user does not have the required authentication. If admin-routes returns nil, user-routes will be tried by compojure.
Hope this helps.
EDIT: I wrote a post about Compojure some time back, which you might find useful: https://vedang.me/techlog/2012-02-23-composability-and-compojure/
I stumbled on this issue, and it seems wrap-routes (compojure 1.3.2) solves elegantly:
(def app
(handler/api
(routes
public-routes
(-> user-routes
(wrap-routes wrap-basic-authentication user-auth?)))))
(-> admin-routes
(wrap-routes wrap-basic-authentication admin-auth?)))))
This is a reasonable question, which I found surprisingly tricky when I ran into it myself.
I think what you want is this:
(defroutes public-routes
(GET "/public-endpoint" [] ("PUBLIC ENDPOINT")))
(defroutes user-routes
(GET "/user-endpoint1" _
(wrap-basic-authentication
user-auth?
(fn [req] (ring.util.response/response "USER ENDPOINT 1"))))
(GET "/user-endpoint2" _
(wrap-basic-authentication
user-auth?
(fn [req] (ring.util.response/response "USER ENDPOINT 1")))))
(defroutes admin-routes
(GET "/admin-endpoint" _
(wrap-basic-authentication
admin-auth? (fn [req] (ring.util.response/response "ADMIN ENDPOINT")))))
(def app
(handler/api
(routes
public-routes
user-routes
admin-routes)))
Two things to note: the authentication middleware is inside the routing form and the middleware calls an an anonymous function that is a genuine handler. Why?
As you said, you need to apply authentication middleware after routing, or the request will never get routed to the authentication middleware! In other words, the routing needs to be on a middleware ring outside the authentication ring.
If you use Compojure's routing forms like GET, and you are applying middleware in the body of the form, then the middleware function needs as its argument a genuine ring response handler (that is, a function that takes a request and returns a response), rather than something simpler like a string or a response map.
This is because, by definition, middleware functions like wrap-basic-authentication only take handlers as arguments, not bare strings or response maps or anything else.
So why is it so easy to miss this? The reason is that the Compojure routing operators like (GET [path args & body] ...) try to make things easy for you by being very flexible with what form you are allowed to pass in the body field. You can pass in a true handler function, or just a string, or a response map, or probably something else that hasn't occurred to me. It's all laid out in the render multi-method in the Compojure internals.
This flexibility disguises what the GET form is actually doing, so it's easy to get mixed up when you try to do something a bit different.
In my view, the problem with the leading answer by vedang is not a great idea in most cases. It essentially uses compojure machinery that's meant to answer the question "Does the route match the request?" (if not, return nil) to also answer the question "Does the request pass authentication?" This is problematic because usually you want requests that fail authentication to return proper responses with 401 status codes, as per the HTTP spec. In that answer, consider what would happen to valid user-authenticated requests if you added such an error response for failed admin-authentication to that example: all the valid user-authenticated request would fail and give errors at the admin routing layer.
I just found the following unrelated page that addresses the same issue:
http://compojureongae.posterous.com/using-the-app-engine-users-api-from-clojure
I didn't realise it's possible to use that type of syntax (which I have not yet tested):
(defroutes public-routes
(GET "/public-endpoint" [] ("PUBLIC ENDPOINT")))
(defroutes user-routes
(GET "/user-endpoint1" [] ("USER ENDPOINT 1"))
(GET "/user-endpoint2" [] ("USER ENDPOINT 1")))
(defroutes admin-routes
(GET "/admin-endpoint" [] ("ADMIN ENDPOINT")))
(def app
(handler/api
(routes
public-routes
(ANY "/user*" []
(-> user-routes
(wrap-basic-authentication user-auth?)))
(ANY "/admin*" []
(-> admin-routes
(wrap-basic-authentication admin-auth?))))))
Have you considered using Sandbar? It uses role-based authorisation, and lets you specify declaratively which roles are needed to access a particular resource. Check Sandbar's documentation for more information, but it could work something like this (note the reference to a fictitious my-auth-function, that's where you'd put your authentication code):
(def security-policy
[#"/admin-endpoint.*" :admin
#"/user-endpoint.*" :user
#"/public-endpoint.*" :any])
(defroutes my-routes
(GET "/public-endpoint" [] ("PUBLIC ENDPOINT"))
(GET "/user-endpoint1" [] ("USER ENDPOINT1"))
(GET "/user-endpoint2" [] ("USER ENDPOINT2"))
(GET "/admin-endpoint" [] ("ADMIN ENDPOINT"))
(def app
(-> my-routes
(with-security security-policy my-auth-function)
wrap-stateful-session
handler/api))
I would shift how you end up handling the authentication in general to split apart the process of authenticating and filtering routes on authentication.
Rather than just having the admin-auth? and user-auth? return booleans or a user name, use it as more of an "access level" key which you can filter on on much more of a per-route level without the need to "reauthenticate" for different routes.
(defn auth [user pass]
(cond
(admin-auth? user pass) :admin
(user-auth? user pass) :user
true :unauthenticated))
You'll also want to consider an alternate to the existing basic authentication middleware for this path. As it's currently designed, it'll always return a {:status 401} if you don't provide credentials, so you'll need to take this into account and have it continue through instead.
The result of this is put in the :basic-authentication key in the request map, which you can then filter at the level you want.
The main "filtering" cases that come to mind are:
At a context level (like what you have in your answer), except you can just filter out requests that don't have the required :basic-authentication key
On a per route level, where you return a 401 response after a local check on how it's authenticated. Note that this is the only way you'll get a distinction between 404s and 401s unless you do the context level filtering on individual routes.
Different views for a page depending on the authentication level
The biggest thing to remember is that you have to continue feeding back nil for invalid routes unless the url being asked for needs authentication. You need to make sure you're not filtering out more than you want by returning a 401, which will cause ring to stop trying any other routes/handles.