openresty 验证
下载代码https://gitee.com/findlp/lua-jwt-token.git
在服务器创建目录/usr/local/openresty/nginx/jwt-lua/resty
把下载的 lua-jwt-token/resty下的所有lua文件拷贝到该目录下
修改nginx.conf
验证是否生效
http {
lua_package_path "/usr/local/openresty/nginx/jwt-lua/?.lua;;";
server {
listen 8080;
default_type text/plain;
location = /verify {
content_by_lua '
local cjson = require "cjson"
local jwt = require "resty.jwt"
local jwt_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" ..
".eyJmb28iOiJiYXIifQ" ..
".VAoRL1IU0nOguxURF2ZcKR0SGKE1gCbqwyh8u2MLAyY"
local jwt_obj = jwt:verify("lua-resty-jwt", jwt_token)
ngx.say(cjson.encode(jwt_obj))
';
}
location = /sign {
content_by_lua '
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)
';
}
}
}
token校验
[root@docker resty]# curl localhost:8080/verify
{"signature":"VAoRL1IU0nOguxURF2ZcKR0SGKE1gCbqwyh8u2MLAyY","reason":"everything is awesome~ :p","valid":true,"raw_header":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9","payload":{"foo":"bar"},"header":{"alg":"HS256","typ":"JWT"},"verified":true,"raw_payload":"eyJmb28iOiJiYXIifQ"}
token生成
[root@docker resty]# curl localhost:8080/sign
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.VxhQcGihWyHuJeHhpUiq2FU7aW2s_3ZJlY6h1kdlmJY
自定义验证逻辑: ngxin-jwt.lua
修改nginx.conf使用
openresty access_by_lua_file 拦截headers校验token
location = / {
access_by_lua_file /usr/local/openresty/nginx/jwt-lua/resty/nginx-jwt.lua;
}
验证
[root@docker resty]# curl localhost:8080
{"payload":{"foo":"bar","iat":1602749860.8605},"reason":"everything is awesome~
:p","raw_header":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9","valid":true,"header":{"alg":"HS256","typ":"JWT"},"signature":"gwlWp1WTBtpNY6awR6SkD3wTtfJ-zhJgWuYBdXXC7VY","verified":true,"raw_payload":"eyJmb28iOiJiYXIiLCJpYXQiOjE2MDI3NDk4NjAuODYwNTA4N30"}
OK.