安装openresty使用nginx+lua,openresty使用jwt解密

cpp 复制代码
yum install -y epel-release
yum update
yum search openresty  # 查看是否有可用包
yum install -y openresty


启动systemctl start openresty

验证服务状态systemctl status openresty

设置开机自启systemctl enable openresty


systemctl stop openresty      # 停止服务
systemctl restart openresty   # 重启服务
systemctl reload openresty    # 重载配置(无需重启服务)

使用

nginx配置文件

cpp 复制代码
location / {
    root   html;
    index  index.html index.htm;
    //直接使用
    //content_by_lua_block {
    //    ngx.say("Hello, OpenResty!")
    //	  ngx.var.uri获得请求地址
    //     ngx.say("Request URI: ", ngx.var.uri)
    // }
    //lua文件
    content_by_lua_file "/usr/local/openresty/nginx/conf/lua/app.lua";
}

app.lua

cpp 复制代码
-- 获取请求参数
local args = ngx.req.get_uri_args()
-- 设置响应头
ngx.header.content_type = "application/json; charset=utf-8"

ngx.say('{"code":2006,"data":[],"message":"请求成功"}')

使用解密

cpp 复制代码
安装
yum install openresty-opm 
安装
opm get SkyLothar/lua-resty-jwt


引入
local jwt = require("resty.jwt")
使用
local secret = "wbrj"  -- JWT签名密钥
local jwt_obj = jwt:verify(secret, headers["token"])

完整案例app.lua文件

cpp 复制代码
-- 获取请求参数
local args = ngx.req.get_uri_args()
-- 设置响应头
ngx.header.content_type = "application/json; charset=utf-8"

-- 引入JSON编码库
local cjson = require("cjson")

local uri = ngx.var.uri

-- 定义不需要拦截的路径数组
local whitelist = {
    "/main/admin/login",
    "/main/admin/wbUrl", --App绑定域名
    "/main/accset/select", --获得套账数
    "/main/accset/select", --获得套账数
    "/wbrjPys/accset/select",--获得套账数
    "/wbrjPys/static" -- 静态文件
}
-- 检查URI是否在白名单中
local in_whitelist = false
for _, path in ipairs(whitelist) do
    if string.find(uri, path) then
        in_whitelist = true
        break
    end
end
-- 如果在白名单中,直接放行
if in_whitelist then
    return
end

-- 获取所有请求头信息
local headers = ngx.req.get_headers()


-- 使用Lua表构建响应数据,code是2006
local response = {
    code = 2001,
    data = {},
    message = "签权失败",
    uri = headers['token']
}
local jwt = require("resty.jwt")

-- 检查请求头中是否存在token字段
if headers["token"] and headers["token"] ~= "" then
    -- 使用示例
    local secret = "dade"  -- JWT签名密钥
    local jwt_obj = jwt:verify(secret, headers["token"])
    
    response['valid'] = jwt_obj
     ngx.say(cjson.encode(response))
else
    --自动编码为JSON字符串,自动处理转义
    ngx.say(cjson.encode(response))
end
相关推荐
一条泥憨鱼15 小时前
【Redis | 黑马点评】分布式锁;Lua脚本;Redisson与看门狗 |源码万字详解
redis·分布式·lua
时间售卖铺16 小时前
Nginx 反向代理
运维·nginx·云原生
life码农16 小时前
Nginx location 优先级详解:匹配规则、修饰符与完整代码示例
运维·nginx
爬也要爬着前进21 小时前
Prometheus通过Nginx-vts-exporter模块监控nginx服务
运维·nginx·prometheus
溪语流沙21 小时前
【Web全栈进阶】Nginx反向代理 + HTTPS:正式上线
前端·vue.js·python·nginx·https·fastapi
无敌糖果1 天前
Nginx 后端error.log疯狂刷盘问题分析
运维·nginx
李纲明2 天前
WordPress 古腾堡点「更新」报「不是有效的 JSON 响应」:我按 REST 接口一路查下来的顺序
运维·nginx·php·wordpress·rest api
你看我名字2 天前
LNMP 生产架构与云运维实践:Nginx、PHP-FPM、MySQL 全链路分析
运维·nginx·架构
疯狂成瘾者2 天前
海康威视 WSS 视频取流原理:6014/559 端口、Nginx 代理与 TLS 证书问题
运维·nginx·音视频
李纲明2 天前
WordPress 首页正常、内页全 404:固定链接与伪静态规则排查步骤(Apache / Nginx)
nginx·apache·wordpress