Openresty使用JWT验证

安装JWT:

# 下载JWT的lua库
wget https://github.com/SkyLothar/lua-resty-jwt/releases/download/v0.1.11/lua-resty-jwt-0.1.11.tar.gz
# 解压
tar -zxvf lua-resty-jwt-0.1.11.tar.gz
# 进入resty目录
cd /opt/openresty/lua-resty-jwt-0.1.11/lib
# 拷贝整个resty目录到openresty的resty目录下
cp -r * /usr/local/openresty/lualib/
# 进入openresty的resty目录下
cd /usr/local/openresty/lualib/resty
# 下载hmac源文件(覆盖刚刚jwt的hmac.lua文件)
wget https://github.com/jkeys089/lua-resty-hmac/blob/master/lib/resty/hmac.lua

JWT:

由header(头部)payload(数据)signature(签名)三部分组成

1.header(头部)

{
    alg:signature部分使用的签名算法,通常可以取两个值
        "HS256":一种对称加密算法,使用同一个秘钥对signature加密解密
        "RS256":一种非对称加密算法,使用私钥加密,公钥解密
    typ:类型,固定写"JWT"即可
}

2.payload(数据,可以自定义私有字段)

{
    iss (issuer):签发人
    exp (expiration time):过期时间
    sub (subject):主题
    aud (audience):受众
    nbf (Not Before):生效时间
    iat (Issued At):签发时间
    jti (JWT ID):编号    
}

3.signature(签名)

对前两部分的签名,使用header里面指定的签名算法

新建auth.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
local jwt = require "resty.jwt"
local cjson = require "cjson"

local M = {
secret = "lua-resty-jwt",
expire = 86400
}
-- 验证
function M.Verify()
-- 获取消息头认证token
local auth_token = ngx.req.get_headers()["authorization"]

if auth_token == nil then
ngx.log(ngx.WARN, "No Auth Token")
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end

-- 验证token
local jwt_obj = jwt:verify(M.secret, auth_token)
if jwt_obj.verified == false then
ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason)
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end

-- 注册
function M.Sign(user_name)
local jwt_token = jwt:sign(
M.secret,
{
header={typ="JWT", alg="HS256"},
payload={name=user_name, exp=ngx.time()+M.expire}
}
)
return jwt_token
end

return M

注意:

一定要用lua-resty-hmac的hmac.lua源文件覆盖lua-resty-jwt的源文件
否则报错:libluajit-5.1.so.2: undefined symbol: HMAC_CTX_init

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!