2025-10-31 21:34:33 +08:00
|
|
|
|
local jwt = require "resty.jwt"
|
|
|
|
|
|
local validators = require "resty.jwt-validators"
|
|
|
|
|
|
local conf = require("config")
|
|
|
|
|
|
|
2025-11-01 15:38:37 +08:00
|
|
|
|
--获取用户认证数据信息
|
2025-10-31 21:34:33 +08:00
|
|
|
|
local auth_header = ngx.var.http_Authorization
|
2025-11-01 15:38:37 +08:00
|
|
|
|
|
|
|
|
|
|
--如果请求头中没有令牌,则直接返回401
|
2025-10-31 21:34:33 +08:00
|
|
|
|
if auth_header == nil or auth_header == "" then
|
|
|
|
|
|
ngx.log(ngx.WARN, "没有找到令牌数据")
|
|
|
|
|
|
ngx.status = ngx.HTTP_UNAUTHORIZED
|
|
|
|
|
|
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
|
|
|
|
|
end
|
2025-11-01 15:38:37 +08:00
|
|
|
|
|
|
|
|
|
|
--查找令牌中的Bearer前缀字符,并进行截取 todo 使用jsonscheme进行匹配
|
2025-10-31 21:34:33 +08:00
|
|
|
|
local _, _, token = string.find(auth_header, "Bearer%s+(.+)")
|
2025-11-01 15:38:37 +08:00
|
|
|
|
--如果没有Bearer,则表示令牌格式不正确
|
2025-10-31 21:34:33 +08:00
|
|
|
|
if token == nil then
|
|
|
|
|
|
ngx.log(ngx.WARN, "令牌格式不正确")
|
|
|
|
|
|
ngx.status = ngx.HTTP_UNAUTHORIZED
|
|
|
|
|
|
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
|
|
|
|
|
end
|
2025-11-01 08:20:23 +08:00
|
|
|
|
|
2025-10-31 21:34:33 +08:00
|
|
|
|
--校验令牌
|
|
|
|
|
|
local jwt_obj = jwt:verify(conf.secret_key, auth_header)
|
|
|
|
|
|
--如果校验结果中的verified==false,则表示令牌无效
|
|
|
|
|
|
if jwt_obj.verified == false then
|
|
|
|
|
|
ngx.log(ngx.WARN, "Invalid token: ".. jwt_obj.reason)
|
|
|
|
|
|
ngx.status = ngx.HTTP_UNAUTHORIZED
|
|
|
|
|
|
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
|
|
|
|
|
end
|
2025-11-01 08:20:23 +08:00
|
|
|
|
|
2025-11-01 15:38:37 +08:00
|
|
|
|
--判断token是否超时 --令牌已过期
|
2025-10-31 21:34:33 +08:00
|
|
|
|
if jwt_obj.payload.exp and os.time() > jwt_obj.payload.exp then
|
|
|
|
|
|
ngx.log(ngx.WARN, "token timeout ".. jwt_obj.reason)
|
|
|
|
|
|
ngx.status = ngx.HTTP_UNAUTHORIZED
|
|
|
|
|
|
ngx.exit(ngx.HTTP_UNAUTHORIZED)
|
|
|
|
|
|
end
|
2025-11-01 08:20:23 +08:00
|
|
|
|
|
2025-10-31 21:34:33 +08:00
|
|
|
|
--全部校验完成后,说明令牌有效,返回令牌数据
|
|
|
|
|
|
ngx.log(ngx.INFO, "令牌校验通过 JWT: " .. cjson.encode(jwt_obj))
|