Compare commits

...

2 Commits

7 changed files with 388 additions and 56 deletions

View File

@ -53,9 +53,21 @@ http {
set $APP_PATH '/home/frankly/work/AuthPlatform';
# 全局 CORS 配置 访问时允许跨域处理
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
# 允许所有域跨域访问(不推荐,出于安全考虑应指定具体域名)
add_header 'Access-Control-Allow-Origin' '*';
# 允许特定域跨域访问(推荐)
#add_header 'Access-Control-Allow-Origin' 'https://xxx.com';
# 允许的HTTP方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
# 允许的自定义请求头
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,Authorization,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Laction';
# 允许的暴露请求头
add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,Authorization,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Location';
# 允许携带Cookie
add_header 'Access-Control-Allow-Credentials' 'true';
# 预检请求的有效期(可选)
add_header 'Access-Control-Max-Age' 1728000;
# 如果请求方法是OPTIONS则直接返回204状态码不执行后续操作
if ($request_method = 'OPTIONS') {
return 204;
}

112
oauth.html Normal file

File diff suppressed because one or more lines are too long

View File

@ -13,6 +13,12 @@ local routes = {
--------------------------------------------
------------ OIDC OAuth2.0认证相关路由配置 ---
--------------------------------------------
--登陆界面
{
paths = { "/yum/v1/oauth/v2/login" },
methods = { "GET" },
handler = oauthService.login,
},
--获取授权码
{
paths = { "/yum/v1/oauth/v2/authorize" },

View File

@ -26,18 +26,41 @@ local function getUriArgs()
ngx.req.read_body()
-- 获取请求数据
local body_data = ngx.req.get_body_data()
-- 验证json数据是否正确
local ok, data = pcall(cjson.decode, body_data)
if not ok then
return ngx.exit(ngx.HTTP_BAD_REQUEST)
print("body_data:", body_data)
local content_type = ngx.req.get_headers()["Content-Type"]
if content_type == "application/x-www-form-urlencoded" then
body_data, err = ngx.req.get_post_args()
if not body_data then
ngx.status = 500
ngx.say("获取表单数据失败: ", err)
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
args = body_data
else
-- 验证json数据是否正确
local ok, data = pcall(cjson.decode, body_data)
if not ok then
print("json err:", ok)
return ngx.exit(ngx.HTTP_BAD_REQUEST)
end
args = data
end
args = data
elseif ngx.req.get_method() == "GET" then
args = ngx.req.get_uri_args()
end
return args
end
function _M:login()
--读取oauth login界面文件
local current_dir = ngx.var.APP_PATH
local html = current_dir.."/oauth.html"
local file = io.open(html, "r")
local content = file:read("*a")
file:close()
ngx.say(content)
end
--获取授权码
function _M:authorize()
local args = getUriArgs()
@ -72,10 +95,7 @@ function _M:authorize()
local user, err = client.validate(client_id, redirect_uri)
if user == nil then
-- 重定向到登录页,携带当前授权请求参数(登录后跳转回来)
--local login_url = "/login?redirect=" .. ngx.escape_uri(ngx.var.request_uri)
--print("authorize login_url:", login_url)
--ngx.redirect(login_url)
resp:response(status.USER_NOT_LOGIN)
self:login()
return
end
-- 4. 生成授权码随机字符串确保唯一性用户ID、客户端ID、scope、生成时间
@ -113,25 +133,37 @@ local function authorizatePassword(args)
local userid = res[1].id
local client_id = args.client_id
local client_secret = args.client_secret
local redirect_uri = args.redirect_uri
code, res = oauthDao.getApplicationByUserid(userid, client_id, client_secret)
if code ~= 0 or res == nil then
resp:response(status.DATA_NONE_FOUNT)
return
end
local redirect_uri = res[1].redirect_uri
local uri_callback = res[1].redirect_uri
-- 4.生成授权码随机字符串确保唯一性用户ID、客户端ID、scope、生成时间
local auth_code, err = authcode.create(userid, client_id, redirect_uri)
local auth_code, err = authcode.create(userid, client_id, uri_callback)
if not auth_code then
ngx.log(ngx.ERR, "生成授权码失败: ", err)
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
-- 5.存储用户信息,证明用户已经登陆
client.create(userid, client_id, redirect_uri)
-- 6.返回结果
local rest = {}
rest.redirect_uri = redirect_uri
rest.code = auth_code
resp:response(status.SUCCESS, rest)
client.create(userid, client_id, uri_callback)
-- 6.Callback 端点用表单 POST 重定向(避免 URL 参数过长)
ngx.status = 302 -- 302 保留请求方法
ngx.header["Location"] = redirect_uri.."?code="..auth_code
ngx.exit(ngx.HTTP_OK)
-- 目标地址:绝对 URL替换为你的实际地址
--local target_url = redirect_uri.."?code="..auth_code --("特殊字符/中文")
--ngx.redirect(target_url, 302)
-- 设置 302 跳转
--ngx.status = 302
--ngx.header["Location"] = target_url
---- 禁用缓存,避免浏览器缓存跳转
--ngx.header["Cache-Control"] = "no-store, no-cache, must-revalidate"
--ngx.header["Pragma"] = "no-cache"
---- 终止请求,确保响应不被覆盖
--ngx.exit(ngx.HTTP_OK)
end
-- 通过code形式进行认证
@ -150,14 +182,14 @@ local function authorizateCode(args)
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
-- 3.验证redirect_url地址的正确性
local request_uri = code_data.redirect_uri
print("token request_uri:", request_uri)
if request_uri ~= args.redirect_uri then
print("token redirect_url:", request_uri, args.redirect_uri)
local login_url = "/login?redirect=" .. ngx.escape_uri(request_uri)
resp:response(status.PARAM_IS_INVALID, login_url)
return
end
local redirect_uri = code_data.redirect_uri
--print("token request_uri:", request_uri)
--if request_uri ~= args.redirect_uri then
-- print("token redirect_url:", request_uri, args.redirect_uri)
-- local login_url = "/login?redirect=" .. ngx.escape_uri(request_uri)
-- resp:response(status.PARAM_IS_INVALID, login_url)
-- return
--end
-- 4.生成密钥对
--local pub_key, priv_key, err = rsa.generate_rsa_keys(2048)
--if err then
@ -193,7 +225,19 @@ local function authorizateCode(args)
return
end
-- 7.返回结果
ret.redirect_uri = redirect_uri
-- 4.返回结果
resp:response(status.SUCCESS, ret)
do return end
--ngx.header["Location"] = redirect_uri;
--ngx.status = ngx.HTTP_MOVED_TEMPORARILY; -- 设置状态码为302
--ngx.say("response body for 302 redirect."); -- 发送自定义消息体
----resp:response(status.MOVED_TEMPORARILY, ret)
--ngx.exec(redirect_uri, { ret = ret })
ngx.status = 302 -- 302 保留请求方法
ngx.header["Location"] = redirect_uri
ngx.exit(ngx.HTTP_OK)
end
-- 刷新令牌
@ -239,7 +283,10 @@ function _M:token()
ngx.exit(ngx.HTTP_BAD_REQUEST)
end
local grant_type = args.grant_type
--print("grant_type类型: ", grant_type)
local client_id = args.client_id
local client_secret = args.client_secret
local redirect_uri = args.redirect_uri
print("grant_type类型: ", grant_type, " client_id:", client_id, " client_secret:", client_secret, " redirect_uri:", redirect_uri)
if grant_type == "password" then
authorizatePassword(args)
elseif grant_type == "authorization_code" then

View File

@ -36,17 +36,6 @@ if not ok then
ngx.say("加载失败"..gd)
return
end
function enabled(res, desc)
local str = " " .. desc .. " "
str = str .. string.rep(".", 37 - string.len(str))
if res then
ngx.say(str .. " Enabled")
else
ngx.say(str .. " Disabled")
end
end
ngx.say("Lua-GD version: " .. gd.VERSION)
ngx.say("Lua-GD features:")
@ -86,6 +75,7 @@ local uuid = require("util.uuid")
local uid = uuid.generateUuid()
ngx.say("uuid:"..uid)
--[[
local genpic = require("util.generatechaptcha")
local filename, fp = genpic.getChaptcha()
--redis中添加picgid为key,string为value的记录
@ -96,6 +86,7 @@ ngx.header.content_type = "text/plain"
ngx.header.picgid = filename
--页面返回pic
ngx.say(fp)
--]]
--nginx退出
--ngx.exit(200)
--do return end
@ -123,6 +114,11 @@ local digest = require "resty.openssl.digest"
local pkey = require "resty.openssl.pkey"
local str = require "resty.string"
local x509 = require "resty.openssl.x509"
local x509_name = require "resty.openssl.x509.name"
local x509_extension = require "resty.openssl.x509.extension"
local altname = require "resty.openssl.x509.altname"
--获取共享字段中的键值
local key = "11-code"
local shared_dict = ngx.shared.codeDict
@ -142,6 +138,7 @@ ngx.say("code:"..code)
ngx.say("-----")
--[[
-- 正确的schema定义
local schema = {
type = "object",
@ -173,16 +170,13 @@ local schemaToken = {
}
-- 原始JSON字符串
--local jsonStr = [[
--{
-- "username": "admin",
-- "password": "123456",
-- "captcha": "",
-- "checkKey": ""
--}
--]]
local jsonStr ={
"username": "admin",
"password": "123456",
"captcha": "",
"checkKey": ""
}
--[[
ngx.req.read_body()
--获取请求数据
local jsonStr = ngx.req.get_body_data()
@ -220,6 +214,7 @@ end
do return end
--]]
--[[
-- 生成RSA密钥对
local function generate_rsa_keys(length)
local key, err = pkey.new({
@ -370,11 +365,9 @@ end
-- 执行示例
example()
--]]
--do
-- return
--end
--[[
-- 公钥加密(用于生成测试数据)
local function rsa_encrypt(pub_key, plaintext)
--
@ -548,6 +541,167 @@ if not decoded then
end
ngx.say("JWT is valid: ", cjson.encode(decoded))
--]]
-- 1. 生成 RSA 私钥2048 位,可改为 4096 提升安全性)
local priv_key, err = pkey.new({
type = "RSA", -- 密钥类型RSA/ECC
bits = 2048, -- 密钥长度
-- 可选ECC 密钥配置(替换 RSA 时使用)
-- type = "EC",
-- curve = "prime256v1", -- P-256 曲线
})
if not priv_key then
error("生成私钥失败: " .. err)
end
-- 2. 构建证书 DNDistinguished Name- 证书主体信息
local dn, err = x509_name.new()
if not dn then
error("构建 DN 失败: " .. err)
end
-- 添加 DN 字段(按实际需求修改)
--local ok, err = dn:add_entry("C", "CN") -- 国家2 字母代码)
--if not ok then error(err) end
--ok, err = dn:add_entry("ST", "Beijing") -- 省份
--if not ok then error(err) end
--ok, err = dn:add_entry("L", "Beijing") -- 城市
--if not ok then error(err) end
--ok, err = dn:add_entry("O", "MyCompany") -- 组织
--if not ok then error(err) end
--ok, err = dn:add_entry("OU", "TechDept") -- 部门
--if not ok then error(err) end
--ok, err = dn:add_entry("CN", "example.com") -- 通用名(证书绑定的域名)
--if not ok then error(err) end
local ok, err = dn:add("C", "CN") -- 国家2 字母代码)
if not ok then error(err) end
ok, err = dn:add("ST", "Beijing") -- 省份
if not ok then error(err) end
ok, err = dn:add("L", "Beijing") -- 城市
if not ok then error(err) end
ok, err = dn:add("O", "MyCompany") -- 组织
if not ok then error(err) end
ok, err = dn:add("OU", "TechDept") -- 部门
if not ok then error(err) end
ok, err = dn:add("CN", "example.com") -- 通用名(证书绑定的域名)
if not ok then error(err) end
-- 3. 创建 X.509 证书对象并配置基础信息
local cert, err = x509.new()
if not cert then
error("创建证书对象失败: " .. err)
end
-- 设置版本X509v3
ok, err = cert:set_version(3) -- 版本号从 0 开始3 对应 X509v3
if not ok then error(err) end
-- 设置序列号(唯一标识,建议用随机数避免冲突)
math.randomseed(os.time())
local serial = math.random(1000000000, 9999999999)
print("serial value:", serial)
ok, err = cert:set_serial_number(serial)
if not ok then error(err) end
-- 设置有效期起始时间当前时间结束时间365 天后)
local not_before = os.date("*t")
local not_after = os.date("*t")
not_after.year = not_after.year + 1 -- 有效期 1 年
ok, err = cert:set_not_before(not_before)
if not ok then error(err) end
ok, err = cert:set_not_after(not_after)
if not ok then error(err) end
-- 设置证书主体和颁发者(自签名:主体 = 颁发者)
ok, err = cert:set_subject_name(dn)
if not ok then error(err) end
ok, err = cert:set_issuer_name(dn)
if not ok then error(err) end
-- 绑定公钥(从私钥中提取)
local pub_key, err = priv_key:get_public_key()
if not pub_key then error("提取公钥失败: " .. err) end
ok, err = cert:set_pubkey(pub_key)
if not ok then error(err) end
-- 4. 配置证书扩展属性(关键!否则证书可能无法被浏览器/客户端信任)
-- 4.1 基本约束(自签名证书设为 CA:FALSE
local ext, err = x509_extension.new(
"basicConstraints", "CA:FALSE", false -- 第三个参数critical是否强制
)
if not ext then error(err) end
ok, err = cert:add_extension(ext)
if not ok then error(err) end
-- 4.2 密钥用途(数字签名、服务器认证等)
ext, err = x509_extension.new(
"keyUsage", "digitalSignature, keyEncipherment", false
)
if not ext then error(err) end
ok, err = cert:add_extension(ext)
if not ok then error(err) end
-- 4.3 扩展密钥用途(服务器/客户端认证)
ext, err = x509_extension.new(
"extendedKeyUsage", "serverAuth, clientAuth", false
)
if not ext then error(err) end
ok, err = cert:add_extension(ext)
if not ok then error(err) end
-- 4.4 主题备用名称SAN支持多域名/IP浏览器优先使用
local san = altname.new()
ok, err = san:add("DNS", "example.com") -- 主域名
ok, err = san:add("DNS", "www.example.com") -- 子域名
ok, err = san:add("IP", "192.168.1.100") -- 绑定 IP可选
if not san then error(err) end
ext, err = x509_extension.new(
"subjectAltName", san:tostring(), false
)
if not ext then error(err) end
ok, err = cert:add_extension(ext)
if not ok then error(err) end
-- 4.5 主题密钥标识(可选,增强安全性)
ext, err = x509_extension.new(
"subjectKeyIdentifier", "hash", false
)
if not ext then error(err) end
ok, err = cert:add_extension(ext)
if not ok then error(err) end
-- 5. 用私钥自签名证书签名算法SHA256withRSA
ok, err = cert:sign(priv_key, "SHA256") -- 算法支持SHA1/SHA256/SHA512推荐 SHA256+
if not ok then
error("签名证书失败: " .. err)
end
-- 6. 导出私钥和证书为 PEM 格式(保存到文件或返回给调用者)
local priv_key_pem, err = priv_key:to_pem("private") -- 私钥 PEM
local public_key_pem, err = pub_key:to_pem("public") -- 公钥 PEM
local cert_pem, err = cert:to_pem() -- 证书 PEM
-- 保存到文件(示例)
--local priv_file = io.open("/path/to/example.key", "w")
--priv_file:write(priv_key_pem)
--priv_file:close()
--
--local cert_file = io.open("/path/to/example.crt", "w")
--cert_file:write(cert_pem)
--cert_file:close()
ngx.say("公钥文件:-----")
ngx.say(pub_key)
ngx.say("私钥文件:-----")
ngx.say(priv_key_pem)
ngx.say("证书文件:-----")
ngx.say(cert_pem)
ngx.say("自签名证书生成成功!")
--print("私钥文件: /path/to/example.key")
--print("证书文件: /path/to/example.crt")
--local original_text = "这是一段需要加密的敏感数据123456"
--local key = x509.PKey()

View File

@ -22,6 +22,7 @@ local _M = {
-- 成功状态码
SUCCESS = { code = 200, message = "操作成功" },
MOVED_TEMPORARILY = { code = 302, message = "跳转URI" },
--[[
HTTP_SPECIAL_RESPONSE(300, "操作成功"),
HTTP_MOVED_PERMANENTLY(301, "操作成功"),

View File

@ -55,8 +55,9 @@ local schemaUserPasswd = {
client_secret = { type = "string" },
username = { type = "string" },
password = { type = "string" },
redirect_uri = { type = "string" },
},
required = { "grant_type", "client_id", "client_secret", "username", "password" }
required = { "grant_type", "client_id", "client_secret", "username", "password", "redirect_uri" }
}
--通过用户名和密码进行认证
@ -72,9 +73,8 @@ local schemaToken = {
properties = {
grant_type = { type = "string" },
code = { type = "string" },
redirect_uri = { type = "string" },
},
required = { "grant_type", "code", "redirect_uri" }
required = { "grant_type", "code" }
}
--根据授权码获取Access-Token