增加token文件用于生成jwt-token和验证token函数,并对用户登陆接口进行修改,用户退出进行日志记录

This commit is contained in:
wanglei 2025-10-31 15:09:03 +08:00
parent 0deb9ad029
commit bbd56036b7
6 changed files with 231 additions and 63 deletions

View File

@ -8,11 +8,12 @@ events {
}
http {
##lua_need_request_body on; #开启读取请求体数据
client_max_body_size 1024M; #允许最大100k的请求体
client_body_buffer_size 1024M; #设置缓冲区大小
lua_package_path '$prefix/src/?/?.lua;$prefix/src/?.lua;;';
lua_package_path '$prefix/src/?/?.lua;$prefix/src/?.lua;/home/frankly/work/AuthPlatform/src/?/?.lua;/home/frankly/work/AuthPlatform/src/?.lua;;';
lua_package_cpath '$prefix/src/share/lib/?.so;;';
# Path of the file with trusted CA certificates.
@ -31,6 +32,7 @@ http {
}
## 应用路径
set $APP_PATH '/home/frankly/work/AuthPlatform';
#登录认证配置
include 'auth/auth.conf';
#数据列表配置
@ -50,7 +52,7 @@ http {
}
#jwt验证进行测试
location /api/test {
access_by_lua_file /usr/local/openresty/lualib/resty/jwt-auth.lua;
access_by_lua_file '${APP_PATH}/src/util/jwt-auth.lua';
proxy_pass http://192.168.147.1:3000;
}
}

View File

@ -11,7 +11,7 @@ local authService = require("service.auth.auth")
--定义相关路由前端接口url地址
local routes = {
--------------------------------------------
-------------用户登录相关路由配置--------------
-------------用户认证相关路由配置--------------
--------------------------------------------
--用户登录路由接口
{
@ -19,12 +19,30 @@ local routes = {
methods = { "POST" },
handler = authService.login,
},
--用户注册路由接口
{
paths = { "/api/auth/signup" },
methods = { "POST" },
handler = authService.signup,
},
--用户退出路由接口
{
paths = { "/api/auth/logout/:id" },
paths = { "/api/auth/logout" },
methods = { "POST" },
handler = authService.logout,
},
--根据token信息获取用户信息数据
{
paths = { "/api/auth/user" },
methods = { "GET" },
handler = authService.user,
},
--根据token信息获取用户权限数据
{
paths = { "/api/auth/permission" },
methods = { "GET" },
handler = authService.permission,
},
}
-- 初始化路由

View File

@ -5,27 +5,12 @@
---
local resp = require("util.response")
local authDao = require("dao.auth")
local jwt = require("resty.jwt")
local conf = require("config")
local validatorJson = require("validator.auth.auth")
local validator = require("validator.auth.auth")
local cjson = require("cjson.safe")
local token = require("util.token")
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.login()
--读取请求体的数据
@ -33,7 +18,46 @@ function _M.login()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local retJson = validatorJson.validatorJson(body_data)
local retJson = validator.validatorJson(body_data)
--验证失败则返回
if not retJson then
local result = resp:json(0x000001)
resp:send(result)
return
end
--ngx.say(body_data)
local code, ret = authDao.login(cjson.decode(body_data))
--读取数据错误
if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001)
resp:send(result)
return
end
local id = ""
local username = ""
for _, row in ipairs(ret) do
id = row.id
username = row.username
end
--获取的登陆的用户信息返回tocken
ngx.log(ngx.INFO, "userid:"..id.." username:"..username)
local jwt_token = token.generateToken(id, username)
local data = {}
data["token"] = jwt_token
data["userInfo"] = ret
local result = resp:json(code, data)
resp:send(result)
end
--用户注册业务逻辑处理
function _M.signup()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local retJson = validator.validatorJson(body_data)
--验证失败则返回
if not retJson then
local result = resp:json(0x000001)
@ -63,21 +87,93 @@ end
--用户登出业务逻辑处理
function _M.logout()
--获取请求头中的令牌数据
local auth_header = ngx.var.http_Authorization
--验证数据的正确性
local ret = token.authorizationToken(auth_header)
--验证失败则返回
local code = ret["code"]
if code ~= 200 then
local result = resp:json(code, ret["message"])
resp:send(result)
return
end
--验证成功记录登出的日志信息
ngx.log(ngx.INFO, cjson.encode(ret["body"]))
local userid = ret["body"]["payload"]["userid"]
local username = ret["body"]["payload"]["username"]
ngx.log(ngx.INFO, "userid:"..userid.." username:"..username.." logout system")
local result = resp:json(0, "用户退出系统成功")
resp:send(result)
end
--根据token获取用户信息
function _M.user()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local ok = validatorJson.validatorJson(body_data)
local retJson = validator.validatorJson(body_data)
--验证失败则返回
if not ok then
if not retJson then
local result = resp:json(0x000001)
resp:send(result)
return
end
--ngx.say(body_data)
local code, ret = authDao.logout(cjson.decode(body_data))
local result = resp:json(code, ret)
local code, ret = authDao.login(cjson.decode(body_data))
--读取数据错误
if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001)
resp:send(result)
return
end
--获取的登陆的用户信息返回tocken
obj.payload.userid = ret["id"]
obj.payload.username = ret["name"]
obj.payload.role = ""
local jwt_token = jwt:sign(conf.secret_key, obj)
--ngx.say(jwt_token)
local data = {}
data["token"] = jwt_token
data["userInfo"] = ret
local result = resp:json(code, data)
resp:send(result)
end
--根据token获取用户登录权限
function _M.permission()
--读取请求体的数据
ngx.req.read_body()
--获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证数据是否符合json
local retJson = validator.validatorJson(body_data)
--验证失败则返回
if not retJson then
local result = resp:json(0x000001)
resp:send(result)
return
end
--ngx.say(body_data)
local code, ret = authDao.login(cjson.decode(body_data))
--读取数据错误
if code ~= 0 or table.getn(ret) < 0 then
local result = resp:json(0x000001)
resp:send(result)
return
end
--获取的登陆的用户信息返回tocken
obj.payload.userid = ret["id"]
obj.payload.username = ret["name"]
obj.payload.role = ""
local jwt_token = jwt:sign(conf.secret_key, obj)
--ngx.say(jwt_token)
local data = {}
data["token"] = jwt_token
data["userInfo"] = ret
local result = resp:json(code, data)
resp:send(result)
end

View File

@ -33,14 +33,26 @@ ngx.say("pageNum:", pageNum, " pageSize:", pageSize)
--]]
local jwttoken = require("validator.auth.auth")
local cjson = require "cjson"
--local sampleJson = [[{"age":"23","testArray":{"array":[8,9,11,14,25]},"Himi":"himigame.com"}]]
local sampleJson = [[{"raw_header":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9","signature":"zkKAmXifqWDrMaLpXe8hrA1JpDRbdlgwS-yxNnQUOBw","raw_payload":"eyJpYXQiOjE3NjE4OTIwNDMsImV4cCI6MTc2MTg5NTY0MywidXNlcmlkIjoiYWRtaW4iLCJyb2xlIjoiIn0","valid":true,"verified":true,"reason":"everything is awesome~ :p","header":{"alg":"HS256","typ":"JWT"},"payload":{"iat":1761892043,"userid":"admin","exp":1761895643,"role":""}}]]
--解析json字符串
local data = cjson.decode(sampleJson);
--打印json字符串中的age字段
ngx.say(data["raw_header"]);
--打印数组中的第一个值(lua默认是从0开始计数)
ngx.say(data["payload"]["userid"]);
--[[
local jwttoken = require("util.token")
--获取请求头中的令牌数据
local auth_header = ngx.var.http_Authorization
--调用令牌校验
local result = jwttoken.check(auth_header)
local result = jwttoken.authorizationToken((auth_header))
-- 输出结果
ngx.say(cjson.encode(result))
ngx.exit(result.code)
--]]
--[[
local jsonschema = require("jsonschema")

75
src/util/token.lua Normal file
View File

@ -0,0 +1,75 @@
---
--- 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是否超时
--全部校验完成后,说明令牌有效,返回令牌数据
response["code"] = 200
response["message"] = "令牌校验通过"
response["body"] = jwt_obj
return response
end
return _M

View File

@ -4,8 +4,6 @@
--- DateTime: 2025/10/30 08:09
---业务逻辑 对账户登录的参数进行数据的验证
local jsonschema = require("jsonschema")
local jwt = require("resty.jwt")
local conf = require("config")
local _M = {}
@ -26,37 +24,4 @@ function _M.validatorJson(jsonData)
return result
end
--令牌校验
function _M.check(auth_header)
--定义响应数据
local response = {}
--如果请求头中没有令牌则直接返回401
if auth_header == nil 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, token)
--如果校验结果中的verified==false则表示令牌无效
if jwt_obj.verified == false then
response["code"] = 401
response["message"] = "令牌无效"
return response
end
--全部校验完成后,说明令牌有效,返回令牌数据
response["code"] = 200
response["message"] = "令牌校验通过"
response["body"] = jwt_obj
return response
end
return _M