Skip to content

Instantly share code, notes, and snippets.

@binhqd
Created January 3, 2018 02:34
Show Gist options
  • Save binhqd/042cfe559886d5023fcf27df5e1cd08a to your computer and use it in GitHub Desktop.
Save binhqd/042cfe559886d5023fcf27df5e1cd08a to your computer and use it in GitHub Desktop.
Nginx jwt verification by lua
local cjson = require "cjson"
local jwt = require "resty.jwt"
local args = ngx.req.get_uri_args()
local token = args.BearerToken
if (args.bearerToken ~= nil) then
token = args.bearerToken
end
if (token == nil or token == "") then
local authorization = ngx.req.get_headers()["Authorization"]
if (authorization ~= nil) then
token = string.sub(authorization, 8)
end
end
local jwt_obj = jwt:load_jwt(token)
local f = io.open("/opt/nginx/conf/certs/client_ssl.pem", "rb")
local content = f:read("*all")
f:close()
local verified = jwt:verify_jwt_obj(content, jwt_obj)
if (verified.valid == false) then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.header["Content-Type"] = 'application/json'
ngx.say(cjson.encode({
status = ngx.HTTP_BAD_REQUEST,
message = "Invalid token"
}))
ngx.exit(ngx.HTTP_BAD_REQUEST)
elseif (verified.verified == false) then
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.header["Content-Type"] = 'application/json'
ngx.say(cjson.encode({
status = ngx.HTTP_UNAUTHORIZED,
message = "Unauthorized. Token may be expired"
}))
ngx.exit(ngx.HTTP_UNAUTHORIZED)
else
return
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment