安装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
相关推荐
羱滒2 小时前
Docker Compose + Nginx + 后端服务运行环境搭建全流程指南(redis、mongdb、nginx、nacos-registry)
redis·nginx·docker·docker-compose
xiaozenbin4 小时前
宝塔8.5在nginx中部署动态php页面出现找不到页面处理
运维·nginx·php
爱莉希雅&&&12 小时前
LVS+Keepalived+DNS+Web+NFS 高可用集群项目完整部署流程
运维·nginx·dns·lvs·keepalived·nfs·ipvsadm
终端行者14 小时前
Nginx limit_conn_zone 模块详解 Nginx如何限流 防止CC攻击
网络·nginx
etp_18 小时前
连击非第一击无伤害
运维·nginx
L16247620 小时前
Nginx+Tomcat+Redis(单节点 / 3 节点集群)+Redisson 共享 Session 完整整合手册
redis·nginx·tomcat
菜鸟厚非1 天前
如何在 Nginx 中配置 HTTPS - Linux
linux·nginx·https
vortex51 天前
php-fpm + nginx 环境搭建配置与常见问题解决
开发语言·nginx·php
周公挚友1 天前
centos 7.9 搭建nginx
linux·nginx·centos
alex18011 天前
nginx配置图片静态路由
数据库·nginx·postgresql