-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccess.lua
More file actions
83 lines (71 loc) · 2.4 KB
/
access.lua
File metadata and controls
83 lines (71 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
-- © Optum 2018
local resty_sha256 = require "resty.sha256"
local str = require "resty.string"
local singletons = require "kong.singletons"
local private_key_location = os.getenv("KONG_SSL_CERT_KEY")
local pl_file = require "pl.file"
local json = require "cjson"
local utils = require "kong.tools.utils"
local openssl_digest = require "openssl.digest"
local openssl_pkey = require "openssl.pkey"
local table_concat = table.concat
local encode_base64 = ngx.encode_base64
local _M = {}
--- base 64 encoding
-- @param input String to base64 encode
-- @return Base64 encoded string
local function b64_encode(input)
local result = encode_base64(input)
result = result:gsub("+", "-"):gsub("/", "_"):gsub("=", "")
return result
end
local function encode_token(data, key)
local header = {typ = "JWT", alg = "RS256"}
local segments = {
b64_encode(json.encode(header)),
b64_encode(json.encode(data))
}
local signing_input = table_concat(segments, ".")
local signature = openssl_pkey.new(key):sign(openssl_digest.new("sha256"):update(signing_input))
segments[#segments+1] = b64_encode(signature)
return table_concat(segments, ".")
end
local function readFromFile(file_location)
local content, err = pl_file.read(file_location)
if not content then
ngx.log(ngx.ERR, "Could not read file contents", err)
return nil, err
end
return content
end
local function getKongPkey()
-- This will add a non expiring TTL on this cached value
-- https://github.com/thibaultcha/lua-resty-mlcache/blob/master/README.md
local pkey, err = singletons.cache:get("pkey", { ttl = 0 }, readFromFile, private_key_location)
if err then
ngx.log(ngx.ERR, "Could not retrieve pkey: ", err)
return
end
return pkey
end
local function add_jwt_header(conf)
local kong_pkey = getKongPkey()
ngx.req.read_body() --Read body before doing get data
local req_body = ngx.req.get_body_data() --Get the data after read complete
local digest_created = ""
if req_body ~= nil then
local sha256 = resty_sha256:new()
sha256:update(req_body)
digest_created = sha256:final()
end
local payload = {
payloadhash = str.to_hex(digest_created),
exp = ngx.time() + 60 --trying this now since above won't work, much better performance improvement over os.time()
}
local jwt = encode_token(payload, kong_pkey)
ngx.req.set_header("JWT", jwt)
end
function _M.execute(conf)
add_jwt_header(conf)
end
return _M