Created
May 31, 2019 12:48
-
-
Save elratt0r/e059aeed5eff5d8a2dab2bfcd1a56728 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local HMAC_SECRET = "add,secret,here" | |
local hmac = require "openssl.hmac" | |
local digest = require "openssl.digest" | |
function string.tohex(str) | |
return (str:gsub('.', function (c) | |
return string.format('%02x', string.byte(c)) | |
end)) | |
end | |
function compute_hmac(msg, expires) | |
local h, r | |
h = hmac.new(HMAC_SECRET, "sha256") | |
r = h:final(string.format("%s%d", msg, expires)) | |
return r:tohex() | |
end | |
function compute_digest(msg) | |
local d, r | |
d = digest.new("sha256") | |
r = d:final(msg) | |
return r:tohex() | |
end | |
verify_status = ngx.var.ssl_client_verify | |
if verify_status == "SUCCESS" then | |
client = compute_digest(ngx.var.ssl_client_cert) | |
expires = ngx.time() + 3600 | |
ngx.header["Set-Cookie"] = { | |
string.format("AccessToken=%s; path=/", compute_hmac(client, expires)), | |
string.format("ClientId=%s; path=/", client), | |
string.format("AccessExpires=%d; path=/", expires) | |
} | |
return | |
elseif verify_status == "NONE" then | |
client = ngx.var.cookie_ClientId | |
client_hmac = ngx.var.cookie_AccessToken | |
access_expires = ngx.var.cookie_AccessExpires | |
if client ~= nil and client_hmac ~= nil and access_expires ~= nil then | |
check_hmac = compute_hmac(client, access_expires) | |
if check_hmac ~= "" and check_hmac == client_hmac and tonumber(access_expires) > ngx.time() then | |
return | |
end | |
end | |
end | |
ngx.exit(ngx.HTTP_FORBIDDEN) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment