diff --git a/hosts/proxy/default/nginx/conf/nginx.conf b/hosts/proxy/default/nginx/conf/nginx.conf index f3714d0..67a9187 100644 --- a/hosts/proxy/default/nginx/conf/nginx.conf +++ b/hosts/proxy/default/nginx/conf/nginx.conf @@ -24,6 +24,22 @@ http { proxy_pass http://backend:5000/secure; } + location /secure/secretUser { + access_by_lua ' + -- this endpoint will only allow users whose jwt contains a claim + -- of "customerId" with a value of "customer1" + local jwt = require("nginx-jwt") + jwt.auth() + + local customerId = jwt.get_claim("customerId") + if customerId == nil or customerId ~= "customer1" then + ngx.exit(ngx.HTTP_UNAUTHORIZED) + end + '; + + proxy_pass http://backend:5000/secure; + } + location /secure/admin { access_by_lua ' local jwt = require("nginx-jwt") diff --git a/nginx-jwt.lua b/nginx-jwt.lua index 482765a..9c6d05c 100644 --- a/nginx-jwt.lua +++ b/nginx-jwt.lua @@ -20,9 +20,7 @@ if os.getenv("JWT_SECRET_IS_BASE64_ENCODED") == 'true' then secret = basexx.from_base64(secret) end -local M = {} - -function M.auth(claim_specs) +function getJwt() -- require Authorization request header local auth_header = ngx.var.http_Authorization @@ -35,6 +33,13 @@ function M.auth(claim_specs) -- require Bearer token local _, _, token = string.find(auth_header, "Bearer%s+(.+)") + return token +end + +local M = {} + +function M.auth(claim_specs) + local token = getJwt() if token == nil then ngx.log(ngx.WARN, "Missing token") @@ -121,4 +126,10 @@ function M.table_contains(table, item) return false end +function M.get_claim(claim) + local jwt_obj = jwt:verify(secret, getJwt()) + + return jwt_obj.payload[claim] +end + return M diff --git a/test/test_integration.js b/test/test_integration.js index c30081c..02b6e3d 100644 --- a/test/test_integration.js +++ b/test/test_integration.js @@ -106,6 +106,32 @@ describe('proxy', function () { }); }); + describe("GET /secure/secretUser", function() { + it("should return a 401 for a a user with the wrong customerId value", function() { + var token = jwt.sign( + { customerId: 'customer2' }, + secret); + + return request(url) + .get('/secure/secretUser') + .headers({'Authorization': 'Bearer ' + token}) + .expect(401) + .end(); + }); + + it("should return a 200 for a user with the correct customerId value", function() { + var token = jwt.sign( + { customerId: 'customer1' }, + secret); + + return request(url) + .get('/secure/secretUser') + .headers({'Authorization': 'Bearer ' + token}) + .expect(200) + .end(); + }); + }); + describe("GET /secure/admin", function () { it("should return 401 when an authenticated user is missing a required claim", function () { var token = jwt.sign(