使用nginx + lua腳本 + redis進行token鑑權

1.問題描述:

最近老大交給我一個任務,使用nginx + lua腳本 + redis 來對從客戶端發來的下載請求進行token的鑑權。該下載請求爲一條帶有token信息的URL,假設URL下載請求所帶的token也會同步存入redis中,現在是爲了防止別人僞造URL請求,需要驗證redis中是否存在該token。

2.整體思路:

  • 1.首先從客戶端傳過來一個帶token的下載請求。
  • 2.nginx提供代理服務,利用location的規則來攔截髮來的下載請求。
  • 3.匹配好的下載請求交由lua腳本處理。
  • 4.在lua腳本連接redis服務器,驗證token是否存在。
  • 5.token存在則驗證通過,交由nginx服務器進行反向代理服務;否則返回報錯信息。

3.下面是token鑑權的時序圖

在這裏插入圖片描述

4.相關代碼

4.1 nginx.conf中的代理集羣
 upstream download{
    server  127.0.0.1:8303;
 }
4.2 location的攔截
下載請求:http://localhost:8082/download/files/04a9b52ec74d46829b4b2296fcadb99a/data?token=b17efb43-292e-4cc9-ac5d-0b46bce059c5
#匹配下載請求前綴, 進行token鑑權
location ~ /download/files/.*?/data {
    default_type 'text/html';
    rewrite_by_lua_file  lua-resty-redis/lib/resty/token.lua;
    proxy_pass  http://download;
 }
4.3 進行鑑權的腳本token.lua
local var = ngx.var
local arg = ngx.req.get_uri_args()
local cjson = require("cjson")
--在table的agr中獲取token, token字符串組合成的key值
if arg ~= nil and arg.token ~= nil and arg.token ~= '' then
  token = "download:files:" .. arg.token 
end

--連接redis
local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000) -- 1 sec

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err, "<br/>")
    return
end

-- 請注意這裏 auth 的調用過程 這是redis設置密碼的
local count
count, err = red:get_reused_times()
if 0 == count then
    ok, err = red:auth(password)
    if not ok then
         ngx.say(cjson.encode({code = 500,message = err}))
        return
    end
elseif err then
    	ngx.say("failed to get reused times: ", err, "<br/>")
    return
end

--redis中若 key 存在返回 1 ,否則返回 0 。
local res, errs = red:exists(token)

if res == 0 then
	local loginfailobj = {code = 500,message = "token is wrong"}
    local loginfailjson = cjson.encode(loginfailobj)
    ngx.say(loginfailjson)
end

在瀏覽器地址欄中輸入模擬的URL請求:http://localhost:8082/download/files/04a9b52ec74d46829b4b2296fcadb99a/data?token=b17efb43-292e-4cc9-ac5d-0b46bce059c5
至此,大功告成。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章