业务场景
如果想使用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
local jwt = require("resty.jwt")
local secret="5pil6aOO5YaN576O5Lmf5q+U5LiN5LiK5bCP6ZuF55qE56yR"
jwttoken = {}
function jwttoken.check(auth_header)
local response = {}
if auth_header == nil then
response["code"]=401
response["message"]="没有找到令牌数据"
return response
end
local _, _, token = string.find(auth_header, "Bearer%s+(.+)")
if token == nil then
response["code"]=401
response["message"]="令牌格式不正确"
return response
end
local jwt_obj = jwt:verify(secret, token)
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"
local cjson = require "cjson"
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测试令牌结果,如下图:
令牌错误输入,结果如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)