apisix~csrf插件

配置信息

{
    key: token的密钥
    expires:过期时间,默认7200(秒)
    name: token在cookie中的名称,默认是apisix-csrf-token
}

插件解释

先在cookie中写入csrf-token

local function gen_sign(random, expires, key)
    local sha256 = resty_sha256:new()

    local sign = "{expires:" .. expires .. ",random:" .. random .. ",key:" .. key .. "}"

    sha256:update(sign)
    local digest = sha256:final()

    return str.to_hex(digest)
end


local function gen_csrf_token(conf)
    local random = math.random()
    local timestamp = ngx_time()
    local sign = gen_sign(random, timestamp, conf.key)

    local token = {
        random = random,
        expires = timestamp,
        sign = sign,
    }

    local cookie = ngx_encode_base64(core.json.encode(token))
    return cookie
end

function _M.header_filter(conf, ctx)
    local csrf_token = gen_csrf_token(conf)
    local cookie = conf.name .. "=" .. csrf_token .. ";path=/;SameSite=Lax;Expires="
                   .. ngx_cookie_time(ngx_time() + conf.expires)
    core.response.add_header("Set-Cookie", cookie)
end

一个csrf-token由随机数,过期时间,签名组成,下面介绍一下这3个参数

  • random 随机数
  • expires 过期时间
  • sign = 上面两个参数+key的sha256的散列数
  • 最后把这三个数进行base64写到cookie里

post,put,delete这些会改变数据状态的请求,需要进行csrf的防护,在postman里可以这样测试

  • scripts里添加脚本
var xsrfCookie = postman.getResponseCookie("apisix-csrf-token");
if (xsrfCookie) {
  pm.environment.set("xsrf-token",   decodeURIComponent(xsrfCookie.value)); // 第一次请求后,正确的token就写到postman的cookie里了,下次post请求带上就对了
}
  • header中添加csrf
  • cookie里的csrf也会被传到apisix
  • 最后将header和cookie里的值进行比较

如果出现apisix-csrf-token被篡改,会返回401

{"error_msg":"csrf token mismatch"}
posted @ 2025-03-25 13:26  张占岭  阅读(40)  评论(0)    收藏  举报