Lua识别Jwt令牌业务

业务场景

如果想使用Lua识别用户令牌,我们需要引入lua-resty-jwt模块,是用于 ngx_lua 和 LuaJIT 的 Lua 实现库,在该模块能实现Jwt令牌生成、Jwt令牌校验,依赖库的地址:https://github.com/SkyLothar/lua-resty-jwt

业务实现

lua-resty-jwt安装

​ 在资料\lua中已经下载好了该依赖库lua-resty-jwt-master.zip,我们将该库文件上传到服务器上,并解压,当然,我们也可以使用opm直接安装lua-resty-jwt,配置lua-resty-jwt之前,我们需要先安装resty和opm。

安装仓库管理工具包:

yum install yum-utils

添加仓库地址:

yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

安装resty:

yum install openresty-resty

安装opm:

yum install openresty-opm

安装Jwt组件:

opm get SkyLothar/lua-resty-jwt

此时lua-resty-jwt安装好了,可以直接使用了。

令牌识别

令牌识别有可能在很多操作都需要用到,所以我们可以创建一个独立的模块,用于识别令牌,文件名字叫token.lua

--依赖jwt库
local jwt = require("resty.jwt")
--秘钥
local secret="5pil6aOO5YaN576O5Lmf5q+U5LiN5LiK5bCP6ZuF55qE56yR"

-- 定义一个名为 jwttoken 的模块
jwttoken = {
    
    }

--令牌校验
function jwttoken.check(auth_header)
    --定义响应数据
    local response = {
    
    }

    --如果请求头中没有令牌,则直接返回401
    if auth_header == nil then
        response["code"]=401
        response["message"]="没有找到令牌数据"
        return response
    end

    --查找令牌中的Bearer前缀字符,并进行截取
    local _, _, token = string.find(auth_header, "Bearer%s+(.+)")

    --如果没有Bearer,则表示令牌无效
    if token == nil then
        response["code"]=401
        response["message"]="令牌格式不正确"
        return response
    end

    --校验令牌
    local jwt_obj = jwt:verify(secret, token)

    --如果校验结果中的verified==false,则表示令牌无效
    if jwt_obj.verified == false then
        response["code"]=401
        response["message"]="令牌无效"
        return response
    end

    --全部校验完成后,说明令牌有效,返回令牌数据
    response["code"]=200
    response["message"]="令牌校验通过"
    response["body"]=jwt_obj
    return response
end

return jwttoken

我们创建一个auth_verify.lua用于识别令牌,代码如下:

ngx.header.content_type="application/json;charset=utf8"

--引入json库
local cjson = require "cjson"

--引入jwt模块
local jwttoken = require "token"

--获取请求头中的令牌数据
local auth_header = ngx.var.http_Authorization

--调用令牌校验
local result = jwttoken.check(auth_header)

-- 输出结果
ngx.say(cjson.encode(result))
ngx.exit(result.code)

nginx.conf配置一个用于校验令牌的地址,代码如下:

#令牌校验
location /token {
    
    
    content_by_lua_file /usr/local/openresty/nginx/lua/auth_verify.lua;
}

令牌测试

我们用上面java生成的令牌进行测试,请求:http://192.168.211.137/token测试令牌结果,如下图:

在这里插入图片描述

令牌错误输入,结果如下:

猜你喜欢

转载自blog.csdn.net/weixin_45525272/article/details/128767689
今日推荐