open-resty 服务安装jwt插件

时间:2024-09-30 09:24:45

作者:程序那点事儿 日期:2023/11/16 22:07


lua-resty-jwt 插件

如果想使用Lua识别用户令牌,我们需要引入lua-resty-jwt模块,是用于 ngx_lua 和 LuaJIT 的 Lua 实现库,在该模块能实现Jwt令牌生成、Jwt令牌校验。

下载好了该依赖库lua-resty-jwt-master.zip,我们将该库文件上传到服务器上,并解压,当然,我们也可以使用opm直接安装lua-resty-jwt

解压安装方式参考上面安装lua-resty-kafka,我们现在使用opm的安装方式

  1. yum install yum-utils #安装仓库管理工具包
  2. yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo #添加仓库地址
  3. yum install openresty-resty #安装resty
  4. yum install openresty-opm #安装opm
  5. opm get SkyLothar/lua-resty-jwt #安装Jwt组件
  6. 如果已经安装好OpenResty,跳过第2、3步(建议使用这种方式,如果代码clone不下来)。

添加一个案例访问

在前面kafka的案例中,我们已经创建了lua目录,现在我们就进入到lua目录开始。

  1. vim token.lua #封装一个token.lua脚本,以便复用
--识别令牌
--依赖resty.jwt库
local jwt = require "resty.jwt"

--定义一个模块
local jwttoken = {}

--秘钥
local secret = "5pil6aOO5YaN576O5Lmf5q+U5LiN5LiK5bCP6ZuF55qE56yR"

function jwttoken.check(auth_header)
        --响应信息
        local response = {}
        --令牌是否为空
        if auth_header == nil then
                response["code"] = 401
                response["message"] = "请登录"
                return response
        end
        --判断令牌格式 Bearer ,正确还要去掉Bearer 
        local _,_,token = string.find(auth_header, "Bearer%s+(.+)")
        if token == nil then
                response["code"] = 402
                response["message"] = "令牌无效"
                return response
        end

        --校验令牌是否正确
        local jwt_obj = jwt:verify(secret,token)
        if jwt_obj.verified == false then
                response["code"] = 403
                response["message"] = "令牌无效"
                return response
        end
        --响应正确信息
        response["code"] = 200
        response["message"] = "令牌有效"
        response["body"] = jwt_obj
        return response
end
return jwttoken
  1. vim auth_verify.lua #创建auth_verify.lua脚本(对外访问)
--判断测试令牌是否有效
--设置编码utf8
ngx.header.content_type="application/json;charset=utf8"

--引入cjson库
local cjson = require "cjson"
--引入token库
local jwttoken = require "token"

--获取令牌(请求头中获取令牌)
local auth_header = ngx.var.http_Authorization

--调用token的check方法
local result = jwttoken.check(auth_header)

--将结果响应给客户端
ngx.say(cjson.encode(result))
  1. vim ../conf/nginx.conf #添加配置
    #lua插件位置
    lua_package_path "/usr/local/openresty/nginx/lua/?.lua;/usr/local/openresty/modules/kafka/lib/?.lua;;";
    server {
        listen       80;
        server_name  localhost;


        location /token {
            content_by_lua_file /usr/local/openresty/nginx/lua/auth_verify.lua;
        }

本项目中自己写的lua脚本在/usr/local/openresty/nginx/lua/目录下,因为我们在该目录下写了两个lua脚本:auth_verify.lua,token.lua,在auth_verify.lua中引入了token.lua模块,所以别忘了在nginx.conf文件中添加如下配置,不然会报如下错误:

  1. nginx -s reload #重启ningx
  2. http://192.168.10.100/token #访问测试,结果如下