APISIX源码解析-插件-外部认证【forward-auth】

forward-auth 外部认证

关键属性

在这里插入图片描述

源码实现

function _M.access(conf, ctx)
    -- 固定传递给authorization服务的请求头
    local auth_headers = {
        ["X-Forwarded-Proto"] = core.request.get_scheme(ctx),
        ["X-Forwarded-Method"] = core.request.get_method(),
        ["X-Forwarded-Host"] = core.request.get_host(ctx),
        ["X-Forwarded-Uri"] = ctx.var.request_uri,
        ["X-Forwarded-For"] = core.request.get_remote_client_ip(ctx),
    }

    -- append headers that need to be get from the client request header
    -- 根据request_headers配置,将client请求头传递给authorization服务
    -- 备注:不能覆盖auth_headers中的请求头
    if #conf.request_headers > 0 then
        for _, header in ipairs(conf.request_headers) do
            if not auth_headers[header] then
                auth_headers[header] = core.request.header(ctx, header)
            end
        end
    end

    local params = {
        headers = auth_headers,
        keepalive = conf.keepalive,
        ssl_verify = conf.ssl_verify,
        method = conf.request_method
    }

    -- 向authorization service请求仅支持GET POST方法
    -- 如果是post方法,将client请求body,也转到authorization service
    if params.method == "POST" then
        params.body = core.request.get_body()
    end

    if conf.keepalive then
        params.keepalive_timeout = conf.keepalive_timeout
        params.keepalive_pool = conf.keepalive_pool
    end

    local httpc = http.new()
    httpc:set_timeout(conf.timeout)

    local res, err = httpc:request_uri(conf.uri, params)

    -- block by default when authorization service is unavailable
    -- 当authorization service不可用时返回403
    if not res then
        core.log.error("failed to process forward auth, err: ", err)
        return 403
    end

    if res.status >= 300 then
        local client_headers = {}
        -- 当认证失败时,根据client_headers配置,将authorization service的请求头返回给client
        if #conf.client_headers > 0 then
            for _, header in ipairs(conf.client_headers) do
                client_headers[header] = res.headers[header]
            end
        end

        core.response.set_header(client_headers)
        return res.status, res.body
    end

    -- append headers that need to be get from the auth response header
    -- 当认证成功时,根据upstream_headers配置,将authorization service的请求头传递给上游,比如x_user_id(认证成功后的生ID)等
    for _, header in ipairs(conf.upstream_headers) do
        local header_value = res.headers[header]
        if header_value then
            core.request.set_header(ctx, header, header_value)
        end
    end
end
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值