AuthPlatform/src/util/token.lua

91 lines
2.7 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
--- 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 jsonschema = require("jsonschema")
local _M = {}
local schema = {
type = 'object',
properties = {
Authorization = {type = 'string', minLength = 10, pattern = 'Bearer\\s+(.+)$'},
}, required = {"Authorization"}
}
--设置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 "Bearer "..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
local validator = jsonschema.generate_validator(schema)
local data = {}
data.Authorization = auth_header
local ok = validator(data)
--如果没有Bearer则表示令牌无效
if not ok then
response["code"] = 401
response["message"] = "令牌格式不正确"
return response
end
--查找令牌中的Bearer前缀字符并进行截取
local token = string.sub(auth_header,8)
--校验令牌
local jwt_obj = jwt:verify(conf.secret_key, token)
--如果校验结果中的verified==false则表示令牌无效
if jwt_obj.verified == false then
response["code"] = 401
response["message"] = "令牌无效"
return response
end
--判断token是否超时
if jwt_obj.payload.exp and os.time() > jwt_obj.payload.exp then
response["code"] = 401
response["message"] = "令牌已过期"
return response
end
--全部校验完成后,说明令牌有效,返回令牌数据
response["code"] = 200
response["message"] = "令牌校验通过"
response["body"] = jwt_obj
return response
end
return _M