如果从来没使用过,可以先参考怎么使用如何使用nginx+lua
使用Lua识别用户令牌,我们需要引入lua-resty-jwt模块,是用于 ngx_lua 和 LuaJIT 的 Lua 实现库,在该模块能实现Jwt令牌生成、Jwt令牌校验,依赖库的地址:github.com/SkyLothar/l…
1)lua-resty-jwt安装
我们可以使用opm直接安装lua-resty-jwt,配置lua-resty-jwt之前,我们需要先安装resty和opm。
安装仓库管理工具包:
yum install -y yum-utils
添加仓库地址:
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
安装resty:
yum install -y openresty-resty
安装opm:
yum install -y openresty-opm
安装Jwt组件:
opm get SkyLothar/lua-resty-jwt
此时lua-resty-jwt安装好了,可以直接使用了。
2)令牌识别
令牌识别有可能在很多操作都需要用到,所以我们可以创建一个独立的模块,用于识别令牌,文件名字叫token.lua
--依赖jwt库
local jwt = require("resty.jwt")
--秘钥
local secret="你生成token的秘钥"
-- 定义一个名为 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用于识别令牌,代码如下:
--测试判断令牌是否有效
--设置编码utf8
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添加lua插件位置
lua_package_path "/usr/local/openresty/nginx/lua/?.lua;/usr/local/openresty/lua-resty-kafka-master/lib/?.lua;;";
nginx.conf配置一个用于校验令牌的地址,代码如下:
#令牌校验vim
location /token {
content_by_lua_file /usr/local/openresty/nginx/lua/auth_verify.lua;
}
3)令牌测试