lua 实现请求签名验证

签名类
--第三方类库
dofile("/usr/local/nginx/lua/resty/sha1.lua");
--调试日志
local function log(msg)
        local file = io.open('/tmp/test', 'a+')
        io.output(file)
        io.write('==========='..msg.."\n")
        io.close(file)
end

local Auth = {}
Auth.__index = Auth

function Auth:new()
        local self = {}
        setmetatable(self, Auth)
        return self
end

function Auth:check(sign)
        if sign ~= nil and sign:find("|") ~= nil then
                local pos = sign:find("|")
                hmac = sign:sub(pos+1)
                expire = sign:sub(0, pos-1)

                --log(expire)    
--sha1 加密key,可以自行约定
                if hmac_sha1("sha1", expire) == hmac and tonumber(expire) >= os.time() then
                        return true;
                end
        end

        return false
end

return Auth



在nginx中调用
access_by_lua_file '/usr/local/nginx/lua/access.lua';

local sign = ngx.var.arg_sign --这个签名可以根据需要传递
local Auth = require "resty.auth"
local auth = Auth:new();
if auth:check(sign) then
        ngx.exec("/inline") --目前接口
else
        ngx.status = 403
        ngx.say("forbidden")
        ngx.exit(ngx.HTTP_OK)
end



参考:
http://www.stavros.io/posts/writing-an-nginx-authentication-module-in-lua/

你可能感兴趣的:(lua 接口签名)