Skip to content

Commit 796784f

Browse files
committed
feat: add validate_claims parameter and validation function for claims
1 parent ac0090d commit 796784f

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

lib/resty/libjwt/utils.lua

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ function _M.get_params(params)
66
jwks_files = {},
77
return_unauthorized_default = true,
88
extract_claims = {},
9+
validate_claims = {},
910
}
1011
if params == nil then
1112
return nil, "params is required"
@@ -20,14 +21,18 @@ function _M.get_params(params)
2021
if params["return_unauthorized_default"] ~= nil then
2122
result.return_unauthorized_default = params["return_unauthorized_default"]
2223
end
23-
2424
if params["extract_claims"] ~= nil then
2525
if type(params["extract_claims"]) ~= "table" then
2626
return nil, "extract_claims is not an array"
2727
end
2828
result.extract_claims = params["extract_claims"]
2929
end
30-
30+
if params["validate_claims"] ~= nil then
31+
if type(params["validate_claims"]) ~= "table" then
32+
return nil, "validate_claims is not an array"
33+
end
34+
result.validate_claims = params["validate_claims"]
35+
end
3136
if type(params["jwks_files"]) ~= "table" then
3237
return nil, "jwks_files is not an array"
3338
end
@@ -67,4 +72,39 @@ function _M.get_token(headers, field_token)
6772
return jwtToken[2], ""
6873
end
6974

75+
function _M.validate_claims(validate_claims, claims)
76+
if not validate_claims then
77+
return ""
78+
end
79+
for claim_name, validation in pairs(validate_claims) do
80+
local claim_value = claims[claim_name]
81+
if claim_value == nil then
82+
return "Claim '" .. claim_name .. "' is missing"
83+
end
84+
if validation.exact ~= nil then
85+
if claim_value ~= validation.exact then
86+
return "Claim '" .. claim_name .. "' must be exactly '" .. validation.exact .. "'"
87+
end
88+
end
89+
if validation.one_of ~= nil then
90+
local found = false
91+
for _, allowed_value in ipairs(validation.one_of) do
92+
if claim_value == allowed_value then
93+
found = true
94+
break
95+
end
96+
end
97+
if not found then
98+
return "Claim '" .. claim_name .. "' must be one of the allowed values"
99+
end
100+
end
101+
if validation.pattern ~= nil then
102+
if not string.match(claim_value, validation.pattern) then
103+
return "Claim '" .. claim_name .. "' does not match required pattern"
104+
end
105+
end
106+
end
107+
return ""
108+
end
109+
70110
return _M

0 commit comments

Comments
 (0)