2025-10-31 15:09:03 +08:00
|
|
|
|
---
|
|
|
|
|
|
--- Generated by EmmyLua(https://github.com/EmmyLua)
|
|
|
|
|
|
--- Created by frankly.
|
|
|
|
|
|
--- DateTime: 2025/10/31 09:29
|
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
|
|
local jwt = require("resty.jwt")
|
|
|
|
|
|
local conf = require("config")
|
|
|
|
|
|
|
|
|
|
|
|
local _M = {}
|
|
|
|
|
|
|
|
|
|
|
|
--设置JWT的有效载荷
|
|
|
|
|
|
local obj = {
|
|
|
|
|
|
header = {typ="JWT", alg="HS256"},
|
|
|
|
|
|
payload = { -- 自定义数据
|
|
|
|
|
|
userid = "", -- 用户id
|
|
|
|
|
|
username = "", -- 用户名
|
|
|
|
|
|
role = "", -- 角色
|
|
|
|
|
|
--iss = "your_issuer", -- 签发者
|
|
|
|
|
|
--sub = "1234567890", -- 主题
|
|
|
|
|
|
exp = os.time() + 3600, -- 过期时间(例如:当前时间+1小时)
|
|
|
|
|
|
iat = os.time() -- 签发时间
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function _M.generateToken(userid, username)
|
|
|
|
|
|
if userid == nil or username == nil then
|
|
|
|
|
|
return ""
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
obj.payload.userid = userid
|
|
|
|
|
|
obj.payload.username = username
|
|
|
|
|
|
--获取的登陆的用户信息,返回tocken
|
|
|
|
|
|
local jwt_token = jwt:sign(conf.secret_key, obj)
|
|
|
|
|
|
return jwt_token
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
--令牌校验
|
|
|
|
|
|
function _M.authorizationToken(auth_header)
|
|
|
|
|
|
--定义响应数据
|
|
|
|
|
|
local response = {}
|
|
|
|
|
|
--如果请求头中没有令牌,则直接返回401
|
|
|
|
|
|
if auth_header == nil or auth_header == "" 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(conf.secret_key, auth_header)
|
|
|
|
|
|
--如果校验结果中的verified==false,则表示令牌无效
|
|
|
|
|
|
if jwt_obj.verified == false then
|
|
|
|
|
|
response["code"] = 401
|
|
|
|
|
|
response["message"] = "令牌无效"
|
|
|
|
|
|
return response
|
|
|
|
|
|
end
|
|
|
|
|
|
--判断token是否超时
|
2025-10-31 16:28:00 +08:00
|
|
|
|
if jwt_obj.payload.exp and os.time() > jwt_obj.payload.exp then
|
2025-10-31 15:45:00 +08:00
|
|
|
|
response["code"] = 401
|
|
|
|
|
|
response["message"] = "令牌已过期"
|
|
|
|
|
|
return response
|
|
|
|
|
|
end
|
2025-10-31 15:09:03 +08:00
|
|
|
|
--全部校验完成后,说明令牌有效,返回令牌数据
|
|
|
|
|
|
response["code"] = 200
|
|
|
|
|
|
response["message"] = "令牌校验通过"
|
|
|
|
|
|
response["body"] = jwt_obj
|
|
|
|
|
|
return response
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
return _M
|