准备 lua-resty-jwt 源码 地址 GitHub - iresty/lua-resty-jwt: JWT For The Great Openresty
openresty 安装包 OpenResty® - 中文官方站
FROM centos:7
ADD openresty-1.17.8.1.tar.gz /
ADD lua-resty-jwt/ /lua-resty-jwt
RUN yum -y install perl gcc make pcre-devel openssl openssl-devel
RUN cd /openresty-1.17.8.1 && ./configure --prefix=/opt/openresty \
--with-luajit \
--add-module=/ngx_cache_purge-2.3 \
--without-http_redis2_module && make && make install && \
ln -sf /dev/stdout /opt/openresty/nginx/logs/access.log && \
ln -sf /dev/stderr /opt/openresty/nginx/logs/error.log
RUN cp /lua-resty-jwt/lib/resty/*.lua /opt/openresty/lualib/resty/ && \
cp /lua-resty-jwt/vendor/resty/*.lua /opt/openresty/lualib/resty/ \
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
ENV LUA_PATH=/lua/?.lua;;
WORKDIR /opt/openresty/nginx/sbin
ENTRYPOINT ["/opt/openresty/nginx/sbin/nginx","-c","/opt/openresty/nginx/conf/nginx.conf","-g","daemon off;"]
nginx配置
# 解密
location /lua {
content_by_lua_file /lua/main.lua;
}
# 加密
location /sign {
content_by_lua_file /lua/tokentest.lua;
}
加密lua代码
ngx.header.content_type="text/html;charset=utf-8"
local cjson = require "cjson"
local jwt = require "resty.jwt"
local jwt_token = jwt:sign(
-- 密钥
"lua-resty-jwt",
{
header={typ="JWT", alg="HS256"},
-- 加密内容
payload={foo="bar"}
}
)
ngx.say(jwt_token)
解密lua代码
ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local jwt = require("resty.jwt")
-- 获取token
local auth_header = ngx.var.http_Authorization
-- 加密密钥
local secret = "5pil6aOO5YaN576O5Lmf5q+U5LiN5LiK5bCP6ZuF55qE56yR"
-- 密钥验证
local jwt_obj = jwt:verify(secret, auth_header)
-- 将jwt验证对象返回,或者编写业务逻辑
ngx.say(cjson.encode(jwt_obj))