CDN中运用OpenResty做有效访问时间校验

转载至:微信公众号 可道技术


需求说明

需要对URL参数中的timestamp字段的值做时间校验,例如半个小时内允许访问,超过指定时长禁止访问。
需要实现一个开关,配置是否开启校验,以及校验的时间长度需要配置。

解决方案—— OpenResty

使用OR来实现。
* 在init阶段实现配置装载
* 在access阶段做校验

1.nginx.conf的http段配置添加

lua_code_cache on;
lua_shared_dict config 1m;
init_by_lua_file '/xxx/init_auth.lua';

2./xxx/init_auth.lua内容

local m3_in_time = "on";
local m3_in_ex_time = 7200;

local config = ngx.shared.config;
config:set("m3_in_time",m3_in_time);
config:set("m3_in_ex_time",m3_in_ex_time);

m3_in_time 配置on/off 开关次功能;
m3_in_ex_time 配置的校验有效时间长度,单位为秒,7200为两个小时;

3.在server配置的access位置配置内容

access_by_lua_file "/xxx/auth_timestamp.lua";


4./xxx/auth_timestamp.lua内容

require 'os'

--format time
function gettime(atime)
   local ay = string.sub(atime,1,4);
   local amon = string.sub(atime,5,6);
   local ad = string.sub(atime,7,8);
   local ah = string.sub(atime,9,10);
   local amin = string.sub(atime,11,12);
   local as = string.sub(atime,13,14);
   return os.time({year=ay,month=amon,day=ad,hour=ah,min=amin,sec=as});
end

function time_auth(args,extime)
   local timestamp = (string.match(args,".*timestamp=([^&]*)"));
   local timestamp_n = gettime(timestamp);
   local lasttime = (tonumber(timestamp_n)+extime)
   local nowtime=os.date("%s");
   if timestamp  == nil then
       ngx.exit(ngx.HTTP_FORBIDDEN);
   end
   if string.len(timestamp) ~= 14 then
       ngx.exit(ngx.HTTP_FORBIDDEN);
   end
   if tonumber(nowtime) > lasttime then
       ngx.exit(ngx.HTTP_FORBIDDEN);
   end
end

-- config
local config = ngx.shared.config;
local m3_in_time=config:get("m3_in_time");
local m3_in_ex_time=config:get("m3_in_ex_time");

-- get uri
local url = ngx.var.uri;
local args = ngx.var.args;
if args ~= nil then
url = url.."?"..args
else
ngx.exit(ngx.HTTP_FORBIDDEN);
end

-- index.m3u8
if m3_in_time == "on" then
   local res_in = string.find(url,"/index.m3u8");
   if res_in ~= nil then
--ngx.log(ngx.ERR, "m3_in_time: on!");
time_auth(args,m3_in_ex_time);
   end
--else
   --ngx.log(ngx.ERR, "index.m3u8: both off!");
end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值