A new session cookie on each request

54 views
Skip to first unread message

Zbigniew Łukasiak

unread,
Jan 26, 2013, 2:51:17 AM1/26/13
to ring-c...@googlegroups.com
What is the difference between:

(def app
  (wrap-session handler))

and

(defn app-bad [request]
  ((wrap-session handler) request))

?

I was thinking that the second exactly the same function - but apparently in that case the wrapper sets a new session cookie on each request.  When I reload the page and view the headers I can see that each response has a Set-Cookie header for 'ring-session' - with a new hash:

Set-Cookie:ring-session=db84a908-6b08-4ae6-863e-de7a2cd2df5d;Path=/

I was doing that 'defn' definition for debugging - I wanted to see the request before the middlewares.


Here is the full program:

(ns ring-session-test.core)

(use 'ring.middleware.session)

(defn handler [request]
  (println (request :session))
  {:status 200
   :headers {"Content-Type" "text/plain"}
   :body "Text"
   :session {:a (rand)}})

(def app
  (wrap-session handler))

(defn app-bad [request]
  ((wrap-session handler) request))

And my project.clj:

(defproject ring-session-test "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :license {:name "Eclipse Public License"
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [ring/ring-core "1.1.6"]
                 [ring/ring-jetty-adapter "1.1.6"]]
  :plugins [[lein-ring "0.8.2"]]
  :ring {:handler ring-session-test.core/app-bad})


I run it with 'lein ring server'.

Cheers,
Zbigniew

James Reeves

unread,
Jan 26, 2013, 7:27:04 AM1/26/13
to ring-c...@googlegroups.com
On 26 January 2013 07:51, Zbigniew Łukasiak <zzb...@gmail.com> wrote:
What is the difference between:

(def app
  (wrap-session handler))

and

(defn app-bad [request]
  ((wrap-session handler) request))

?

If you don't set a session store, wrap-session create an in-memory session store one for you when you call the middleware. So the two examples you give could be rewritten as:

  (def app
    (let [store (memory-store)]
      (wrap-session handler {:store memory-store})))

  (defn app-bad [request]
    (let [store (memory-store)
      (wrap-session handler {:store memory-store})))

This should make it clear that in the latter case, you're constructing a new store each time the function is called. If you want it to use the same store, you need to define it outside the function:

  (defonce session-store (memory-store))

  (defn app-bad [request]
    (wrap-session handler {:store memory-store}))

- James

Zbigniew Łukasiak

unread,
Jan 26, 2013, 8:05:11 AM1/26/13
to ring-c...@googlegroups.com, ja...@booleanknot.com
Thanks for such a clear explanation :)

Cheers,
Z.
 
- James

Reply all
Reply to author
Forward
0 new messages