Skip to content

Instantly share code, notes, and snippets.

@lxfontes
Created August 20, 2015 03:12
Show Gist options
  • Select an option

  • Save lxfontes/b917766ccccccd126b38 to your computer and use it in GitHub Desktop.

Select an option

Save lxfontes/b917766ccccccd126b38 to your computer and use it in GitHub Desktop.
openresty jwt proxy
lua_package_path "/etc/nginx/lua/?.lua;;";
lua_shared_dict kids 10m;
server {
server_name google.com www.google.com;
location /_/token {
internal;
proxy_pass http://127.0.0.1:5000;
}
location / {
set $target '';
proxy_set_header Host $host;
access_by_lua_file '/etc/nginx/proxy.lua';
proxy_pass http://127.0.0.1:5000;
}
}
local cjson = require "cjson"
local jwt = require "resty.jwt"
local cache_ttl = 60 * 1000
local req_headers = ngx.req.get_headers()
local token = req_headers.authorization
if not token then
return ngx.exit(504)
end
local jwt_token = string.match(token, "Bearer (.*)$")
if not jwt_token then
return ngx.exit(504)
end
local jwt_obj = jwt:load_jwt(jwt_token)
if not jwt_obj.valid then
return ngx.exit(403)
end
local kid = jwt_obj.payload.kid
if not kid then
return ngx.exit(403)
end
local jwt_secret = ngx.shared.kids:get(kid)
if not jwt_secret then
local res = ngx.location.capture("/_/token?kid=" .. kid)
if (res.status ~= ngx.HTTP_OK) then
return ngx.exit(500)
end
jwt_secret = res.body
ngx.shared.kids:set(kid, jwt_secret, cache_ttl)
end
local jwt_verified = jwt:verify_jwt_obj(jwt_secret, jwt_obj)
if not jwt_verified then
return ngx.exit(403)
end
#!/usr/bin/env python
# pip install flask
# pip install python_jwt
from flask import Flask, request
import jwt
app = Flask(__name__)
@app.route("/_/token")
def token():
print(request.args.get("kid"))
return "secret"
@app.route("/")
def root():
try:
auth = request.headers.get("Authorization")
_, token = auth.split(' ', 2)
jwt_token = jwt.process_jwt(token)
print(jwt_token)
return repr(jwt_token)
except Exception as e:
print(e)
return "wha?"
if __name__ == "__main__":
app.debug = True
app.run()
@lxfontes

Copy link
Copy Markdown
Author
[root@localhost nginx]# curl -H'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImtpZCI6InRlc3QifQ._4wbyexQsKFN-ih5ZHNRpN2Nn6intwOQeEGWPmD0K2c' -H'Host: www.google.com' localhost/
({u'alg': u'HS256', u'typ': u'JWT'}, {u'admin': True, u'kid': u'test', u'sub': u'1234567890', u'name': u'John Doe'})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment