Skip to content

Commit a7e28d0

Browse files
committed
customizations for use with keycloak and server side session storage (redis/shm) to allow server side session data to be modified without invalidating client cookies
1 parent d006e52 commit a7e28d0

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

lib/resty/session.lua

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,9 +150,14 @@ end
150150
local function save(session, close)
151151
session.expires = time() + session.cookie.lifetime
152152
local i, e, s = session.id, session.expires, session.storage
153-
local k = hmac(session.secret, i .. e)
153+
local k = hmac(session.secret, i)
154154
local d = session.serializer.serialize(session.data)
155-
local h = hmac(k, concat{ i, e, d, session.key })
155+
local dkey
156+
if session.data.id_token ~= nil and session.data.id_token.sub ~= nil and session.data.id_token.sub ~= "" then
157+
ngx.log(ngx.DEBUG, "using session.data.id_token.sub in place of d in hmac: ", session.data.id_token.sub)
158+
dkey = session.data.id_token.sub
159+
end
160+
local h = hmac(k, concat{ i, e, dkey or d, session.key })
156161
local cookie, err = s:save(i, e, session.cipher:encrypt(d, k, i, session.key), h, close)
157162
if cookie then
158163
return setcookie(session, cookie)
@@ -306,12 +311,27 @@ function session.open(opts)
306311
self.opened = true
307312
local cookie = getcookie(self)
308313
if cookie then
314+
ngx.log(ngx.DEBUG, "cookie present: ", cookie)
309315
local i, e, d, h = self.storage:open(cookie, self.cookie.lifetime)
310316
if i and e and e > time() and d and h then
311-
local k = hmac(self.secret, i .. e)
317+
ngx.log(ngx.DEBUG, "cookie session data retrieved")
318+
ngx.log(ngx.DEBUG, "i: " .. ngx.encode_base64(i))
319+
ngx.log(ngx.DEBUG, "e: " .. e .. " (time: " .. time() .. ")")
320+
ngx.log(ngx.DEBUG, "d: " .. ngx.encode_base64(d))
321+
ngx.log(ngx.DEBUG, "h: " .. ngx.encode_base64(h))
322+
local k = hmac(self.secret, i)
323+
ngx.log(ngx.DEBUG, "k: " .. ngx.encode_base64(k))
312324
d = self.cipher:decrypt(d, k, i, self.key)
313-
if d and hmac(k, concat{ i, e, d, self.key }) == h then
325+
local dkey, ds = nil, d
326+
if d then
327+
ngx.log(ngx.DEBUG, "d decrypted: " .. d)
314328
d = self.serializer.deserialize(d)
329+
if d.id_token ~= nil and d.id_token.sub ~= nil and d.id_token.sub ~= "" then
330+
ngx.log(ngx.DEBUG, "using d.id_token.sub in place of d in hmac: ", d.id_token.sub)
331+
dkey = d.id_token.sub
332+
end
333+
end
334+
if ds and hmac(k, concat{ i, e, dkey or ds, self.key }) == h then
315335
self.id = i
316336
self.expires = e
317337
self.data = type(d) == "table" and d or {}
@@ -320,6 +340,7 @@ function session.open(opts)
320340
end
321341
end
322342
end
343+
ngx.log(ngx.DEBUG, "no cookie or invalid session, regenerating and flushing session")
323344
regenerate(self, true)
324345
return self, false
325346
end

0 commit comments

Comments
 (0)