若依+lua+jwt校验+反向代理

1.环境安装
2.参考文章
3.base64编码网站

1.进入编码网站将secret加密,复制到application.yml和lua脚本中

2.编写脚本,这里没有再从redis校验一次token。

-- nginx-jwt.lua


local cjson = require "cjson"
local jwt = require "resty.jwt"

--your secret
--local secret = "abcdefghijklmnopqrstuvwxyz"
local secret = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo="

local M = {}


function M.auth()
    -- require Authorization request header
    local auth_header = ngx.var.http_Authorization

    if auth_header == nil then
        ngx.log(ngx.WARN, "No Authorization header")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end

    ngx.log(ngx.INFO, "Authorization: " .. auth_header)

    -- require Bearer token
    local _, _, token = string.find(auth_header, "Bearer%s+(.+)")

    if token == nil then
        ngx.log(ngx.WARN, "Missing token")
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
    ngx.log(ngx.INFO, "Token: " .. token)
    local jwt_obj = jwt:verify(ngx.decode_base64(secret), token)
    if jwt_obj.verified == false then
        ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason)
        ngx.status = ngx.HTTP_UNAUTHORIZED
        ngx.header.content_type = "application/json; charset=utf-8"
        ngx.say(cjson.encode(jwt_obj))
        ngx.exit(ngx.HTTP_UNAUTHORIZED)
    end
    ngx.log(ngx.INFO, "JWT: " .. cjson.encode(jwt_obj))
end

return M

3.根据后端随机生成的tag,进行反向代理

tag是一串乱码存在redis中的乱码,
039672fcb8dd4069bfbd47219244cb1f:192.168.10.1:3306
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by weimingzhong.
--- DateTime: 2023/3/7 10:23
---
-- 获取请求url
local request_uri =ngx.var.request_uri

local serverId=""

-- 分割字符串函数
local function split(str,separator)
    local str = tostring(str)
    local separator = tostring(separator)
    local strB, arrayIndex = 1, 1
    local targetArray = {}
    if (separator == nil)
    then
        return false
    end
    local condition = true
    while (condition)
    do
        si, sd = string.find(str, separator, strB)
        if (si)
        then
            targetArray[arrayIndex] = string.sub(str,strB,si - 1)
            arrayIndex = arrayIndex + 1
            strB = sd + 1
        else
            targetArray[arrayIndex] = string.sub(str,strB,string.len(str))
            condition = false
        end
    end
    return targetArray
end

-- 路径k,v tag放在url第三个位置
local url_split_str = split(request_uri,"/")
for k, v in pairs(url_split_str) do
    if k == 3
    then
        serverId = v
    end
end

ngx.log(ngx.NOTICE, "...................................serverId:",serverId)

local function close_redis(red)
    if not red then
        return
    end
    local pool_max_idle_time = 10000 --毫秒  
    local pool_size = 100 --连接池大小  
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size) 
    if not ok then
        ngx.say("close redis error : ",err);
    end
end

-- 连接redis
local redis = require "resty.redis";
local red = redis:new();
red:set_timeout(2000)

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

-- 请注意这里 auth 的调用过程 这是redis设置密码的
local res, err = red:auth("")
if not res then
  ngx.say("failed to authenticate: ", err)
  return
end

-- 选择数据库
red:select(10)

-- redis中若 key 存在返回
local resp, err = red:get(serverId.."_vnc")
if not resp then  
    ngx.say("get msg error : ", err)
    return close_redis(red)
end  
if resp == ngx.null then  
   return close_redis(red)
end
ngx.log(ngx.NOTICE, "...................................resp:",resp)
local url_split_param = split(request_uri,serverId)
--for k, v in pairs(url_split_param) do
--    ngx.log(ngx.NOTICE, "...................................key:",k)
--    ngx.log(ngx.NOTICE, "...................................value:",v)
--end

-- 从redis取出的字符串 带"" 需要截取一下
ngx.log(ngx.NOTICE, "...................................request_uri:","http://"..string.sub(resp,2,string.len(resp)-1) ..url_split_param[2])

ngx.var.backend="http://"..string.sub(resp,2,string.len(resp)-1) ..url_split_param[2]

4.ngnix配置

http块添加

 #添加websocket参数
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
        }
            location /vnc-api/ {
	    #调试模式(即关闭lua脚本缓存)
	    lua_code_cache off;
#	    #校验token
#	    access_by_lua_block {
#	    	   package.path = package.path..';/usr/local/openresty/lua/?.lua;';
#	    	   local jwt = require('bigdata-nginx-jwt');
#	        jwt.auth();
#	    }
            set $backend '';
		  #lua脚本
            rewrite_by_lua_file '/usr/local/openresty/lua/bigdata-ngnix-vnc.lua';
	       proxy_pass $backend;
	}

    location /ttyd-api/ {
	    #调试模式(即关闭lua脚本缓存)
	    lua_code_cache off;
#	    #校验token
#	    access_by_lua_block {
#	    	   package.path = package.path..';/usr/local/openresty/lua/?.lua;';
#	    	   local jwt = require('bigdata-nginx-jwt');
#	        jwt.auth();
#	    }
            set $backend '';
		  #lua脚本
            rewrite_by_lua_file '/usr/local/openresty/lua/bigdata-ngnix-ttyd.lua';
            # 指定版本为下面两行做准备,下面两行代理ttyd窗口的websockt
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
	       proxy_pass $backend;
	}
	
    location /websockify {
	    #调试模式(即关闭lua脚本缓存)
	    lua_code_cache off;
#	    #校验token
#	    access_by_lua_block {
#	    	   package.path = package.path..';/usr/local/openresty/lua/?.lua;';
#	    	   local jwt = require('bigdata-nginx-jwt');
#	        jwt.auth();
#	    }
		  #转发代理后端地址
            set $backend '';
		  #lua脚本
            rewrite_by_lua_file '/usr/local/openresty/lua/bigdata-ngnix-vnc.lua';
            # 指定版本为下面两行做准备,下面两行代理vnc窗口的websockt
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
 	       proxy_pass $backend;
	}

版权声明:本文为qq_43751489原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。