Skip to content

Commit

Permalink
feat: add JWT decoding functionality with header and payload parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
infezek committed Feb 20, 2025
1 parent 75abc7f commit 17a6736
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions lib/resty/libjwt/utils.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
local b64 = require("ngx.base64")
local cjson = require("cjson.safe")
local _M = {}

function _M.get_params(params)
Expand All @@ -22,7 +24,6 @@ function _M.get_params(params)
return result, ""
end


function _M.split(str, sep)
if str == "" or str == nil then
return nil, "param is required"
Expand All @@ -47,12 +48,45 @@ function _M.get_token(headers, field_token)
return nil, "token not found"
end
if err ~= "" then
return nil, err
return nil, err
end
if jwtToken[2] == nil then
return nil, "token not found"
end
return jwtToken[2], ""
end

return _M
function _M.decode_jwt(jwt)
local header_b64, payload_b64, signature_b64 = jwt:match("([^%.]+)%.([^%.]+)%.([^%.]+)")
if not (header_b64 and payload_b64 and signature_b64) then
error("JWT invalid")
end

local header, err = b64.decode_base64url(header_b64)
if err then
return nil, err
end

local payload, err = b64.decode_base64url(payload_b64)
if err then
return nil, err
end

local header_json = cjson.decode(header)
if not header_json then
return nil, "Failed to parse header JSON"
end

local claim_json = cjson.decode(payload)
if not claim_json then
return nil, "Failed to parse payload JSON"
end

return {
header = header_json,
claim = claim_json,
signature_b64 = signature_b64,
}, nil
end

return _M

0 comments on commit 17a6736

Please sign in to comment.