zhangrui.i
zhangrui.i
发布于 2024-03-01 / 10 阅读
0
0

Openresty 鉴权lua脚本

鉴权lua脚本


local json = require "cjson.safe"
-- 声明鉴权请求路径,需根据实际情况进行修改
local PATH_CHECK_TOKEN = '/auth-server/v1/oauth/check-token'
-- 鉴权白名单,即无需鉴权url请求前缀
local NO_AUTH_ARRAY = {"/api/public/","/v1/3rd/","/ws/ioae/","/api/office/","/api/wps/file/open/","/api/kdxf/meeting/open/","/vendor/","/demo/","/actuator/","/api/vir/demo/","/swagger-ui.html","/webjars/","/v2/","/vir/manage/callbackUrl","/actuator/","/swagger-resources/" }

-- first try to find JWT/Simple token as url parameter e.g. ?token=BLAH
local token = ngx.var.arg_token

local request_uri = ngx.var.request_uri
-- 检测token是否正常
function checkToken()

    -- next try to find JWT/Simple token as Cookie e.g. token=BLAH
    if token == nil then
        token = ngx.var.cookie_token
    end

    -- try to find JWT token in Authorization header Bearer string
    if token == nil then
        local auth_header = ngx.var.http_Authorization
        if auth_header then
            _, _, token = string.find(auth_header, "Bearer%s+(.+)")
        end
    end

    -- finally, if still no JWT/Simple token, kick out an error and exit
    if token == nil then
        ngx.status = ngx.HTTP_UNAUTHORIZED
        ngx.header.content_type = "application/json; charset=utf-8"
        ngx.say("{\"error\": \"missing JWT/Simple token or Authorization header\"}")
        ngx.log(ngx.ERR,"token is nil")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

    -- jwt token will by jwks in application
    local req_param = json.encode({access_token=token})
    local res = ngx.location.capture(PATH_CHECK_TOKEN, {
            method = ngx.HTTP_POST,
            body = req_param
        })
    if res.status ~= 200 then
        ngx.header.content_type = "application/json; charset=utf-8"
        ngx.say('{"code": 0,"msg": "check_token failed."}')
        ngx.exit(ngx.HTTP_OK)
    end
    local body_json = json.decode(res.body)
    if body_json.status == true then
        ngx.req.set_header("xr-uid", body_json.data.uid)
    else
       ngx.say(res.body)
       ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

end
-- 检测是否需要鉴权
function checkAuth()
    local isAuth = true
    for key,value in ipairs(NO_AUTH_ARRAY)
    do
        if string.find(request_uri,value) ~= nil  then
            isAuth = false
            goto label
        end
    end
    ::label::
    return isAuth
end
if  checkAuth() == true then
    checkToken()
end

Nginx配置修改

server {
    listen       8080;
    server_name  localhost;
    # 全部location生效放在此处即可
    #access_by_lua_file /usr/local/openresty/lualib/check-token.lua;
    location / {
            root   html;
            index  index.html index.htm;
        }
    # 调试auth-server(go)鉴权 
    location /go-auth/ {
      access_by_lua_file /usr/local/openresty/lualib/check-token.lua;
      alias /www/;
      try_files   $uri $uri/ @router;
      index  index.html index.htm;
    }
    # 调试auth-server(go)鉴权
    location /go-auth-server/ {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Credentials' 'true';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,X-token,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

      if ($request_method = 'OPTIONS') {
        return 200;
      }
      proxy_pass http://10.23.119.209:8088/auth-server/;
      proxy_pass_header Server;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Scheme $scheme;
    }
    location @router {
          rewrite ^.*$ /index.html last;
    }
    error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
           root   html;
    }
}

存在的问题

有个漏洞: 即url中只要存在白名单中的字段,即放过鉴权;
local start,end = string.find(ngx.var.request_uri,value)
可判断start是否=1

说明

使用sudo yum install -y openresty方式安装openresty后, 需使用openresty替换nginx,如重启nginx可使用openresty -s reload


评论