nginx+lua+redis做访问鉴权

  图片服务器不符合安全

  主要参考链接:

  • https://blog.csdn.net/qq_27156945/article/details/104019069
  • https://blog.csdn.net/liz9411/article/details/102934568?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

一、安装

  需要安装的组件:LuaJIT-2.0.4ngx_devel_kitlua-nginx-module、lua-resty-redis-master。前3个令nginx支持lua,而且需要编译nginx。第4个让lua能访问redis

  1. LuaJIT需要下载、编译、安装,不赘述。需要关注的是直接make和install会安装到/usr/local目录
  2. 编译nginx,不赘述。需要关注2点:
    1. 执行./configure命令时,要指定路径:--add-module=/usr/local/src/ngx_devel_kit-0.3.1 --add-module=/usr/local/src/lua-nginx-module-0.10.9rc7 ;以及with-ld-opt参数:--with-ld-opt='-Wl,-rpath,/usr/local/lib,-z,relro -Wl,-z,now -pie',其中粗体的用来指明luajit的库位置。
    2. 如果是对现有nginx进行补丁,那就make后把nginx覆盖过去。不要make install
  3. lua脚本位置:nginx的配置文件中在http小结中需要配置:lua_package_path "/etc/nginx/lua/lib/?.lua;;";这里的/etc/nginx/lua/lib/是手工创建,把几个组件中的.lua文件都集中过来了

二、代码

  nginx的配置文件,此处仅用了access模块,其他content、head等可以根据实际情况使用

    location ^~ /group1/M01/ {

        default_type 'text/html';
        access_by_lua_file  /etc/nginx/lua/lib/access.lua;

        proxy_pass http://filesvr;
        proxy_redirect default;
        port_in_redirect off;
    }

  lua脚本,此处仅连接redis,检查是否存在该token,未做进一步权限鉴别。

local function close_redis(red)
    if not red then
        return
    end
    local ok,err = red:close();
    if not ok then
        ngx.say("close redis error : ",err);
    end
end


local redis = require("redis");

local red = redis:new();
red:set_timeout(1000)

local ip = "redis srv ip"
local port = 6379

local ok,err = red:connect(ip,port)
if not ok then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local res, err = red:auth("passwd")
if not res then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local ok, err = red:select(3)
if not ok then
  --500
  ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end

local token = ngx.var.arg_token
if token ~= nil and token ~= "" then
  local res, errs = red:exists(token)
  close_redis(red)
  if res == nil then
    --500
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
  end
  if res==0 then
    --401
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
  else
    return
  end
else
  --403
  ngx.exit(ngx.HTTP_FORBIDDEN)
end

三、坑

  仅记录耗时间最久的几个:

  • 运行时报找不到"resty.core",原因是高版本luajit强制使用resty.core,即使使用lua_load_resty_core off;也无法跳过。我是使用lua-nginx-module.v0.10.9rc7来解决。安装resty应该也能解决。
  • lua脚本在require("redis");处报no file '/***/redis.lua。其实不是找不到该文件,而是文件属性没加x。
原文地址:https://www.cnblogs.com/badwood316/p/13900312.html