local cjson = require "cjson" --# https://github.com/SkyLothar/lua-resty-jwt --$ opm get SkyLothar/lua-resty-jwt local jwt = require "resty.jwt" local function cleanupString(str, remove) local lcSubStrTab = {} while true do local lcPos = string.find(str, remove) if not lcPos then lcSubStrTab[#lcSubStrTab + 1] = str break end local lcSubStr = string.sub(str, 1, lcPos - 1) lcSubStrTab[#lcSubStrTab + 1] = lcSubStr str = string.sub(str, lcPos + 1, #str) end local lcMergeStr = "" local lci = 1 while true do if lcSubStrTab[lci] then lcMergeStr = lcMergeStr .. lcSubStrTab[lci] lci = lci + 1 else break end end return lcMergeStr end local function verifyJwtToken(token) local htyuc = ngx.var.htyuc local htyhost = ngx.req.get_headers().HtyHost local http = require "resty.http" local httpc = http.new() local verify_jwt_url = string.format("%s/api/v1/uc/verify_jwt_token", htyuc) ngx.log(ngx.INFO, 'HTYUC VERIFY_JWT_TOKEN_URL -> ' .. verify_jwt_url) local res, err = httpc:request_uri( verify_jwt_url, { ssl_verify = false, -- 设置参数 ssl_verify 为false 不校验ssl证书 method = "POST", headers = { ['HtyHost'] = htyhost, ["Authorization"] = token, }, } ) if not res then ngx.log(ngx.ERR, "CAN'T VERIFY JWT TOKEN -> ", err) ngx.exit(ngx.HTTP_FORBIDDEN) else if 200 ~= res.status then ngx.log(ngx.ERR, "JWT TOKEN VERIFICATION *ERROR* -> ", err) ngx.say(res.body) ngx.exit(res.status) end end ngx.log(ngx.INFO, "JWT TOKEN VERIFICATION *PASSED*.") end local function decodeJwtClaim(jwtClaim) local jwtKey = "0xCAFEBABE0xCAFEBABE0xCAFEBABE0xCAFEBABE0xCAFEBABE0xCAFEBABE" local jwtObj = jwt:verify(jwtKey, jwtClaim) if jwtObj.verified == false then ngx.log(ngx.WARN, "INVALID TOKEN -> " .. jwtObj.reason) ngx.status = ngx.HTTP_UNAUTHORIZED ngx.header.content_type = "application/json; charset=utf-8" ngx.say(cjson.encode(jwtObj)) ngx.exit(ngx.HTTP_UNAUTHORIZED) end ngx.log(ngx.INFO, "DECODED JWT CLAIM -> " .. cjson.encode(jwtObj)) local htyToken = cjson.decode(jwtObj.payload.sub) ngx.log(ngx.INFO, "DECODED JWT TOKEN -> " .. cjson.encode(htyToken)) return htyToken end local function verify(authHeader, sudoerToken) if authHeader then ngx.log(ngx.INFO, 'CHECK_AUTH_HEADER -> ', authHeader) -- local token = decodeJwtClaim(authHeader) verifyJwtToken(authHeader) elseif sudoerToken then ngx.log(ngx.INFO, 'CHECK_SUDOER_HEADER -> ', sudoerToken) -- local token = decodeJwtClaim(sudoerToken) verifyJwtToken(sudoerToken) else ngx.log(ngx.ERR, 'NO AUTH/SUDOER HEADERS!') ngx.status = 500 ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) end end return verify