lua实现nginx带缓存的鉴权

部署lua 参考nginx配置lua脚本_一杯米酒-CSDN博客

部署完成后,就需开始编写脚本了,本人搞了1天

1.更改nginx的支持自定义header(重要,否则无法获得自定义header)

在http{}中 加 :underscores_in_headers on;

在http{}中加:lua_shared_dict tokens 10m;#代表最大10m

2.配置lua文件

server{}中 加 access_by_lua_file xxx你的lua脚本地址;#推荐在conf下建lua目录

3.安装对应库

我这里用到 http 请求 和json 所以 安装了 resty.http json

可以直接下载resty可直接扔到lib库,json则以文件形式引入,随便放

 

4.进行编码 主要使用了ngx.shared.DICT,入需多台nginx协作,可接入redis

-- ngx.say("in")
-- 存储 token _
local tokens=ngx.shared.tokens
-- 清空过期的token
 fn= tokens:flush_expired(0)

local token = ngx.var.cookie_cds_token
if(token==nil)
then
        token=ngx.req.get_headers()["cds_token"]
end
-- ngx.say(token)
-- token为空直接报错
if(token == nil)
then
	local resNullTable={};
	resNullTable["code"]=-1
	resNullTable["msg"]="未登录的请求"
	resNullTable["data"]=""
	JSON = (loadfile "lua/JSON.lua")()
	ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
	ngx.say(JSON:encode(resNullTable))
	ngx.exit(200)
end
-- 是否有缓存
uid = tokens:get(token)
-- ngx.say(uid)
if(uid==nil)
then
	-- 进行http请求检查token
	-- ngx.say("start http!")
	local http = require("resty.http")
	local httpc = http.new()
	local url = "http://10.10.1.42:7106/api/check_token?token="..token
	local res,err = httpc:request_uri(url,{method="GET",headers = {
				["Content-Type"] = "application/json",
			}})
	JSON = (loadfile "lua/JSON.lua")()
	local resStr = res.body
	httpc:close()
	-- ngx.say(resStr)
	local resTable = JSON:decode(resStr)
	-- ngx.say("222")
	if (resTable["data"]~=0)
	then
	-- 校验成功 进行缓存 并设置_uid
	--      ngx.say("go set uid ")
			tokens:set(token,resTable["data"],3)
			uid=resTable["data"]
	end
	if(resTable["data"]==0)
	then
			-- 输出到前端鉴权失败
			resTable["code"]=-1
			ngx.header['Content-Type'] = 'text/plain; charset=utf-8';
			ngx.say(JSON:encode(resTable))
			ngx.exit(200)
	end

end


local paramTable = ngx.req.get_uri_args()
paramTable["_uid"] = uid
ngx.req.set_uri_args(paramTable)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值