openresty在nginx基础上集成了很多功能,比如可以直接调用redis,mysql,http接口等服务,比较流行的网关kong就是通过openresty实现的。日常开发和运维离不开nginx,实现稍微复杂的功能:简单权限控制,灰度发布等就可以通过openresty实现。
本文通过openresty定时器定期请求http接口获取更新的黑名单数据,过滤用户并做进一步的判断(结合实际的业务需求)进行权限管控。话不多说,直接上nginx.conf代码如下。
user root;
worker_processes auto;
worker_cpu_affinity auto;
error_log logs/error.log error;
worker_rlimit_nofile 30000;
pid logs/nginx.pid;
events {
use epoll;
worker_connections 65535;
}
http {
#include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
server_tokens off;
underscores_in_headers on;
keepalive_timeout 10;
send_timeout 60;
include /usr/local/nginx/conf/online/*.conf;
#下面四行和lua相关,重点看一下
lua_shared_dict portalcache 10m;#多进程共享内存变量
lua_shared_dict commoncache 1m;
init_by_lua_file /home/www/example/lua/api_init.lua;#初始化全局变量
init_worker_by_lua_file /home/www/example/lua/api_timer.lua; #启动定时器定期调用接口
upstream portalbackend {
server xxx weight=3;
server xxx weight=1;
}
upstream labelbackend {
server xxx;
server xxx;
}
upstream portalbackendonqlikticket {
server xxx;
server xxx;
}
upstream portalclient {
server xxx;
server xxx;
}
upstream portaladmin {
server xxx;
server xxx;
}
upstream labelfrontend {
server xxx;
server xxx;
}
upstream bigscreen {
server xxx;
server xxx;
}
upstream mobile {
server xxx;
server xxx;
}
upstream portalmobile {
server xxx;
server xxx;
}
server {
listen 80;
server_name localhost hportal-uat.hikvision.com.cn;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://portalclient;
proxy_redirect off;
proxy_set_header host $host;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
add_header access-control-allow-origin *;
add_header access-control-allow-methods 'get, post, put, delete, opt ions';
add_header access-control-allow-credentials 'true';
add_header access-control-allow-headers 'dnt,x-mx-reqtoken,keep-aliv e,user-agent,x-requested-with,if-modified-since,cache-control,content-type,autho rization,origin,accept';
}
location /ptclient {
proxy_pass http://portalclient/ptclient;
proxy_redirect off;
proxy_set_header host $host;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
add_header access-control-allow-origin *;
add_header access-control-allow-methods 'get, post, put, delete, opt ions';
add_header access-control-allow-credentials 'true';
add_header access-control-allow-headers 'dnt,x-mx-reqtoken,keep-aliv e,user-agent,x-requested-with,if-modified-since,cache-control,content-type,autho rization,origin,accept';
}
location /ptadmin {
proxy_pass http://portaladmin/ptadmin;
proxy_redirect off;
proxy_set_header host $host;
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
}
location /api/ {
#...............error.log......notice
rewrite_log on;
#...............
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://portalbackend;
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header host $host;
proxy_set_header origin '';
proxy_set_header x-real-ip $remote_addr;
proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header upgrade $http_upgrade;
proxy_set_header connection "upgrade";
add_header access-control-allow-origin *;
add_header access-control-allow-methods 'get, post, put, delete, options';
add_header access-control-allow-credentials 'true';
add_header access-control-allow-headers 'dnt,x-mx-reqtoken,keep- alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,a uthorization,origin,accept';
}
location /api/checkvmpermission {
default_type text/html;
access_by_lua_file /home/www/example/lua/api_access.lua;
}
location /api/test {
content_by_lua_block {
local portalcache = ngx.shared.portalcache;
ngx.say(portalcache:get("useraccountlist"))
}
}
location @router{
rewrite ^.*$ /index.html last;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
#上述代码段中的接口只需要关注 /api/checkvmpermission和/api/test 即可。
api_init.lua代码如下所示:
json = require "cjson.safe"
http = require("resty.http")
interval = 60
portalcache = ngx.shared.portalcache
iplist = {"xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx"......}
portalcache:set("flag", true)
portalcache:set("iplist", json.encode(iplist))
api_timer.lua代码如下所示:
local function newclient()
local httpc = http.new()
return httpc
end
local handler = function (premature)
local httpc = newclient()
local resp,err = httpc:request_uri("http://10.10.10.10:8080", {
method = "get",
path = "/xxx/xxx",
--请求的校验字段
headers = {
["vm_header"] = "xxxxx"
}
})
--array为类型table,需要序列化之后才能存入portalcache
local array = json.decode(resp.body).data
portalcache:set("useraccountlist", json.encode(array))
end
--只有一个进程负责定时任务
if 0 == ngx.worker.id() then
local ok, err = ngx.timer.every(interval, handler)
if not ok then
log(err, "failed to get useraccountlist: ", err)
return
end
end
api_access.lua代码如下所示:
function account_is_include(value, tab)
--string 转table
local table = json.decode(tab)
for k,v in ipairs(table) do
if string.lower(v) == string.lower(value) then
return true
end
end
return false
end
function ip_is_include(value, tab)
for k,v in ipairs(tab) do
if string.find(value, v) ~= nil then
return true
end
end
return false
end
local function newclient()
local httpc = http.new()
return httpc
end
local handler = function (premature)
local httpc = newclient()
local resp,err = httpc:request_uri("http://xx.xx.xx.xx:xxxx", {
method = "get",
path = "/xxx/xxx",
headers = {
["vm_header"] = "xxx"
}
})
local array = json.encode(json.decode(resp.body).data)
portalcache:set("useraccountlist", array)
end
--nginx启动时先调用一次
if portalcache:get("flag") then
portalcache:set("flag", false)
handler()
end
check_useraccount = portalcache:get("useraccountlist")
check_ip = json.decode(portalcache:get("iplist"))
if nil == check_useraccount or nil == check_ip then
return ngx.exit(500)
end
local headers = ngx.req.get_headers()
local useraccount = headers["useraccount"]
if useraccount == nil then
return ngx.exit(401)
end
if account_is_include(useraccount, check_useraccount) then
local clientip = headers["x-forwarded-for"]
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = headers["proxy-client-ip"]
end
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = headers["wl-proxy-client-ip"]
end
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = ngx.var.remote_addr
end
-- ...............ip......ip,..ip..','..
if clientip ~= nil and string.len(clientip) >15 then
local pos = string.find(clientip, ",", 1)
clientip = string.sub(clientip,1,pos-1)
end
if clientip == nil then
return ngx.exit(500)
end
if ip_is_include(clientip, check_ip) then
return ngx.say(useraccount .. " " .. "welcome to hportal! (vm-ip:" .. clientip ..")")
else
ngx.status = 403
ngx.say("error! restricted permissions! your ip is " .. clientip .. ". make sure your ip is within this range: " .. json.encode(check_ip))
end
else
ngx.say(useraccount .. " " .. "welcome to hportal!")
end
最后实现效果如下所示:


常见问题汇总:
1.init_worker_by_lua_file error: /usr/local/openresty/lualib/resty/http.lua:133: api disabled in the context of init_worker_by_lua*
stack traceback:
[c]: in function 'ngx_socket_tcp'
/usr/local/openresty/lualib/resty/http.lua:133: in function 'new'
/home/www/example/lua/api_timer.lua:6: in function 'newclient'
/home/www/example/lua/api_timer.lua:21: in function 'getuseraccounttask'
/home/www/example/lua/api_timer.lua:35: in main chunk
答:在init_worker_by_lua...中不能直接调报表http的函数,必须在定时器里面调用。
2.json.decode(resp.body).data (table类型)无法直接放入公共缓存变量的value中
答:set时需要将table转为string,get时再转为table。
3. 如何访问http接口
答:推荐使用httpc,openresty本身不支持,需要在/usr/local/openresty/lualib/resty目录下引入以下三个文件:https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty

4.如何获取请求真实ip地址?
local headers=ngx.req.get_headers()
local clientip = headers["x-forwarded-for"]
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = headers["proxy-client-ip"]
end
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = headers["wl-proxy-client-ip"]
end
if clientip == nil or string.len(clientip) == 0 or clientip == "unknown" then
clientip = ngx.var.remote_addr
end
-- 对于通过多个代理的情况,第一个ip为客户端真实ip,多个ip按照','分割
if clientip ~= nil and string.len(clientip) >15 then
local pos = string.find(clientip, ",", 1)
clientip = string.sub(clientip,1,pos-1)
end到此这篇关于nginx+lua(openresty)实现黑/白名单权限控制的示例的文章就介绍到这了,更多相关nginx 黑/白名单权限控制内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论