• -------------------------------------------------------------
  • ====================================

OpenResty 操作cookies

nginx_lua dewbay 6年前 (2019-04-12) 6610次浏览 已收录 2个评论 扫描二维码

在 or 中简单的使用cookies 复杂的操作请使用 lua_resty_cookies

基本操作
获取一个cookies, cookies的 name 叫做 session

local cookie_name = "cookie_session"
ngx.say(ngx.var[cookie_name])


设置 cookies

ngx.header["Set-Cookie"] = "session=af54; Path=/; Expires=" .. 
ngx.cookie_time(ngx.time() + 86400)


测试代码

    location ~ /header_add {
        content_by_lua_block {
            ngx.header["Set-Cookie"] = "session=lzz; Path=/; Expires=" ..
                                       ngx.cookie_time(ngx.time() + 86400)
            ngx.say("orangleliu")
        }
    }看看效果

curl -i 127.0.0.1:8001/header_add

HTTP/1.1 200 OK
Server: openresty/1.9.7.1
Date: Fri, 16 Dec 2016 07:00:30 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: session=lzz; Path=/; Expires=Sat, 17-Dec-16 07:00:30 GMT

set cookie 使用的是直接操作 header 的方式,这个时候如果单独添加一个 cookie 就会覆盖掉其他的值,所以需要多做一些处理。

function get_cookies()
local cookies = ngx.header["Set-Cookie"] or {}
if type(cookies) == "string" then
cookies = {cookies}
end
return cookies
end

function add_cookie(cookie)
local cookies = get_cookies()
table.insert(cookies, cookie)
ngx.header['Set-Cookie'] = cookies
end

add_cookie("session=aff12d; Path=/")

⚠️:上面的代码需要在 header_filter 阶段运行,在这个阶段可以获取 应用或者是后端 proxy 设置的 cookies, 如果你想要 添加,删除,替换某一个 cookies,注意不要覆盖所有的 cookies 了。

删除 cookies 跟上面类似
一个例子,在 content 阶段设置了多个 cookies,然后在 header_filter 阶段删除 cookies

    location ~ /header_delete {
        content_by_lua_block {
            ngx.header["Set-Cookie"] = {'Foo=abc; path=/', 'age=18; path=/'}
            ngx.say("openresty")
        }

        header_filter_by_lua_block {
            local match = string.match

            local function get_cookies()
                -- local cookies = ngx.header["Set-Cookie"] or {}
                local cookies = ngx.header.set_cookie or {}
                if type(cookies) == "string" then
                    cookies = {cookies}
                end
                return cookies
            end

            local function remove_cookie(cookie_name)
                local cookies = get_cookies()

                ngx.log(ngx.ERR, "source cookies ", table.concat(cookies, " "))
                for key, value in ipairs(cookies) do
                    local name = match(value, "(.-)=")
                    ngx.log(ngx.ERR, key.."<=>", value)
                    if name == cookie_name then
                        table.remove(cookies, key)
                    end
                end

                ngx.header['Set-Cookie'] = cookies or {}
                ngx.log(ngx.ERR, "new cookies ", table.concat(cookies, " "))
            end

            remove_cookie("Foo")
        }
    }

}

测试下

curl ‘127.0.0.1:8001/header_delete’ -i

HTTP/1.1 200 OK
Server: openresty/1.9.7.1
Date: Fri, 16 Dec 2016 08:07:34 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: age=18; path=/



其他需求
在做 proxy_pass 之后想给请求统一修改 cookies 值这么做呢?反正都很类似了。。
使用 header_filter_by_lua 指令

header_filter_by_lua '
local cookies = ngx.header.set_cookie
if cookies then
if type(cookies) ~= "table" then
cookies = {cookies}
end
local gsub = string.gsub
local changed
for i, cookie in ipairs(cookies) do
local new_cookie = gsub(cookie, "^target%-cookie=[^;]*", "target-cookie=myvalue", 1)
if new_cookie ~= cookie then
cookies[i] = new_cookie
changed = true
end
end
if changed then
ngx.header.set_cookie = cookies
end
end
';

露水湾 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:OpenResty 操作cookies
喜欢 (3)
[]
分享 (0)
关于作者:
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(2)个小伙伴在吐槽
  1. Stem cell therapy has proven itself to be one of the most effective treatments for Parkinson's Disease. IMC is the leader in stem cell therapies in Mexico. For more information on how we can treat Parkinson's Disease please visit:https://bit.ly/parkinson-integramedicalcenter
    Shaun Winneke2020-08-12 01:28 回复 Windows 10 | Chrome 63.0.3239.26
  2. Greetings, I was just taking a look at your site and filled out your feedback form. The contact page on your site sends you messages like this to your email account which is why you are reading through my message right now correct? This is half the battle with any kind of online ad, getting people to actually READ your ad and that's exactly what I just accomplished with you! If you have something you would like to blast out to lots of websites via their contact forms in the US or to any country worldwide send me a quick note now, I can even target particular niches and my charges are very affordable. Send a reply to: denzeljax219@gmail.com
    Tina Ward2020-08-17 17:38 回复 Windows 10 | Chrome 63.0.3239.26