-- nginx-jwt.lua
local cjson = require "cjson"
local jwt = require "resty.jwt"
--your secret
local secret = "yoursecrethere"
--无需鉴权api清单
local no_need_token_api_list = {'/api/register', '/api/login'}
local function ignore_url (val)
for index, value in ipairs(no_need_token_api_list) do
if (value == val) then
return true
end
end
return false
end
local m = {}
function m.auth()
if ignore_url(ngx.var.request_uri) then
return
else
end
-- require authorization request header
local auth_header = ngx.var.http_authorization
if auth_header == nil then
ngx.log(ngx.warn, "no authorization header")
ngx.exit(ngx.http_unauthorized)
end
-- require bearer token
local _, _, token = string.find(auth_header, "bearer%s+(.+)")
if token == nil then
ngx.log(ngx.err, "missing token")
ngx.exit(ngx.http_unauthorized)
end
--decode_base64和后端保持一致
local jwt_obj = jwt:verify(ngx.decode_base64(secret), token)
if jwt_obj.verified == false then
ngx.log(ngx.err, "invalid token: ".. jwt_obj.reason)
ngx.status = ngx.http_unauthorized
ngx.say(cjson.encode(jwt_obj))
ngx.header.content_type = "application/json; charset=utf-8"
ngx.exit(ngx.http_unauthorized)
end
end
return m