Skip to content

Lua script for Nginx that performs reverse proxy auth using JWT's

License

Notifications You must be signed in to change notification settings

markvnext/nginx-jwt

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JWT Auth for Nginx

nginx-jwt is a Lua script for the Nginx server (running the HttpLuaModule) that will allow you to use Nginx as a reverse proxy in front of your existing set of HTTP services and secure them (authentication/authorization) using a trusted JSON Web Token (JWT) in the Authorization request header, having to make little or no changes to the backing services themselves.

Key Features

  • Secure an existing HTTP service (ex: REST API) using Nginx reverse-proxy and this script
  • Authenticate an HTTP request with the verified identity contained with in a JWT
  • Optionally, authorize the same request using helper functions for asserting required JWT claims

Install

It is recommended to use the latest ngx_openresty bundle directly as this script (and its dependencies) depend on components that are installed by openresty.

Install steps:

  1. Build the Lua script dependencies using this command:

    ./build deps

    This will create a local lib/ directory that contains all Lua scripts that the nginx-jwt script depends on.

    NOTE: This command should work on Mac OS as well as Ubuntu.

  2. Deploy the nginx-jwt.lua script as well as the local lib/ directory (generated in the previous step) to one directory on your Nginx server.

  3. Specify this directory's path using ngx_lua's lua_package_path directive:

    # nginx.conf:
    
    http {
        lua_package_path "/path/to/lua/scripts;;";
        ...
    }
  4. Export the JWT_SECRET environment variable on the Nginx host, setting it equal to your JWT secret. Then expose it to Nginx server:

    # nginx.conf:
    
    env JWT_SECRET;
  5. If your JWT secret is Base64 (URL-safe) encoded, export the JWT_SECRET_IS_BASE64_ENCODED environment variable on the Nginx host, setting it equal to true. Then expose it to Nginx server:

    # nginx.conf:
    
    env JWT_SECRET_IS_BASE64_ENCODED;

Usage

Now we can start using the script in reverse-proxy scenarios to secure our backing service. This is done by using the access_by_lua directive to call the nginx-jwt script's auth() function before executing any proxy_* directives:

# nginx.conf:

server {
    location /secure_this {
        access_by_lua '
            local jwt = require("nginx-jwt")
            jwt.auth()
        ';

        proxy_pass http://my-backend.com$uri;
    }
}

If you attempt to cURL the above /secure_this endpoint, you're going to get a 401 response from Nginx since it requires a valid JWT to be passed:

curl -i http://your-nginx-server/secure_this
HTTP/1.1 401 Unauthorized
Server: openresty/1.7.7.1
Date: Sun, 03 May 2015 18:05:00 GMT
Content-Type: text/html
Content-Length: 200
Connection: keep-alive

<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>openresty/1.7.7.1</center>
</body>
</html>

To create a valid JWT, we've included a handy tool that will generate one given a payload and a secret. The payload must be in JSON format and at a minimum should contain a sub (subject) element. The following command will generate a JWT with an arbitrary payload and the specific secret used by the proxy:

test/sign '{"sub": "flynn"}' 'My JWT secret'
Payload: { sub: 'flynn' }
Secret: JWTs are the best!
Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwZXRlIiwiaWF0IjoxNDMwNjc3NjYzfQ.Zt4qnQyljbqLvAN7BQSuu14z5PjKcPpZZY85hDFVN3E

You can then use the above Token (the JWT) and call the Nginx server's /secure_this endpoint again:

curl -i http://your-nginx-server/secure_this -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwZXRlIiwiaWF0IjoxNDMwNjc3NjYzfQ.Zt4qnQyljbqLvAN7BQSuu14z5PjKcPpZZY85hDFVN3E'
HTTP/1.1 200 OK
Server: openresty/1.7.7.1
Date: Sun, 03 May 2015 18:34:18 GMT
Content-Type: text/plain
Content-Length: 47
Connection: keep-alive
X-Auth-UserId: flynn
X-Powered-By: Express
ETag: W/"2f-8fc49de2"

The reverse-proxied response!

In this case the Nginx server has authorized the caller and performed a reverse proxy call to the backing service's endpoint. Notice too that the nginx-jwt script has tacked on an extra response header called X-Auth-UserId that contains the value passed in the JWT payload's subject. This is just for convenience, but it does help verify that the server does indeed know who you are.

The jwt.auth() function used above can actually do a lot more. See the API Reference section for more details.

API Reference

auth

Syntax: auth([claim_specs])

Authenticates the current request, requiring a JWT bearer token in the Authorization request header. Verification uses the value set in the JWT_SECRET (and optionally JWT_SECRET_IS_BASE64_ENCODED) environment variables.

If authentication succeeds, then by default the current request is authorized by virtue of a valid user identity. More specific authorization can be accomplished via the optional claim_specs parameter. If provided, it must be a Lua Table where each key is the name of a desired claim and each value is a pattern that can be used to test the actual value of the claim. If your claim value is more complex that what a pattern can handle, you can pass an anonymous function instead that has the signature function (val) and returns a truthy value (or just true) if val is a match. You can also use the table_contains helper function to easily check for an existing value in an array table.

For example if we wanted to ensure that the JWT had an aud (Audience) claim value that started with foo: and a roles claim that contained a marketing role, then the claim_specs parameter might look like this:

# nginx.conf:

server {
    location /secure {
        access_by_lua '
            local jwt = require("nginx-jwt")
            jwt.auth({
                aud="^foo:",
                role=function (val) return jwt.table_contains(val, "marketing") end
            })
        ';

        proxy_pass http://my-backend.com$uri;
    }
}

and if our JWT's payload of claims looked something like this, the above auth() call would succeed:

{
    "aud": "foo:user",
    "roles": [ "sales", "marketing" ]
}

NOTE: the auth function should be called within the access_by_lua or access_by_lua_file directive so that it can occur before the Nginx content phase.

table_contains

Syntax: table_contains(table, item)

A helper function that checks to see if table (a Lua Table) contains the specified item. If it does, the function returns true; otherwise false. This is particularly helpful for checking for a value in an array:

array = { "foo", "bar" }
table_contains(array, "foo") --> true

Tests

The best way to develop and test the nginx-jwt script is to run it in a virtualized development environment. This allows you to run Ngnix separate from your host machine (i.e. your Mac) in a controlled execution environment. It also allows you to easily test the script with any combination of Nginx proxy host configurations and backing services that Nginx will reverse proxy to.

This repo contains everything you need to do just that. It's set up to run Nginx as well as a simple backend server in individual Docker containers.

Prerequisites (Mac OS)

  1. boot2docker
    NOTE: if you want to install boot2docker using Homebrew, checkout these instructions
  2. Node.js

Build and run the default containers

If you just want to see the nginx-jwt script in action, you can run the backend container and the default proxy (Nginx) container:

./build run

NOTE: On the first run, the above script may take several minutes to download all the base Docker images, so go grab a fresh cup of coffee. Successive runs are much faster.

You can then run cURL commands against the endpoints exposed by the backend through Nginx. The root URL of the proxy is reported back by the script when it is finished. It will look something like this:

...
Proxy:
curl http://192.168.59.103

Notice the proxy container (which is running in the boot2docker VM) is listening on port 80. The actual backend container is not directly accessible via the VM. All calls are configured to reverse-proxy through the Nginx host and the connection between the two is done via docker container linking.

If you issue the above cURL command, you'll hit the proxy's root (/) endpoint, which simply reverse-proxies to the non-secure backend endpoint, which doesn't require any authentication:

curl -i http://192.168.59.103
HTTP/1.1 200 OK
Server: openresty/1.7.7.1
Date: Sun, 03 May 2015 18:05:10 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 16
Connection: keep-alive
X-Powered-By: Express
ETag: W/"10-574c3064"

Backend API root

However, if you attempt to cURL the proxy's /secure endpoint, you're going to get a 401 response from Nginx since it requires a valid JWT:

curl -i http://192.168.59.103/secure
HTTP/1.1 401 Unauthorized
Server: openresty/1.7.7.1
Date: Sun, 03 May 2015 18:05:00 GMT
Content-Type: text/html
Content-Length: 200
Connection: keep-alive

<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>openresty/1.7.7.1</center>
</body>
</html>

Just like we showed in the Usage section, we can use the included sign tool to generate a JWT and call the Nginx proxy again, this time with a 200 response:

test/sign '{"sub": "flynn"}' 'JWTs are the best!'
Payload: { sub: 'flynn' }
Secret: JWTs are the best!
Token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwZXRlIiwiaWF0IjoxNDMwNjc3NjYzfQ.Zt4qnQyljbqLvAN7BQSuu14z5PjKcPpZZY85hDFVN3E
curl -i http://192.168.59.103/secure -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJwZXRlIiwiaWF0IjoxNDMwNjc3NjYzfQ.Zt4qnQyljbqLvAN7BQSuu14z5PjKcPpZZY85hDFVN3E'
HTTP/1.1 200 OK
Server: openresty/1.7.7.1
Date: Sun, 03 May 2015 18:34:18 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 47
Connection: keep-alive
X-Auth-UserId: flynn
X-Powered-By: Express
ETag: W/"2f-8fc49de2"

{"message":"This endpoint needs to be secure."}

The proxy exposes other endpoints, which have different JWT requirements. To see them all, take a look at the default proxy's nginx.conf file.

If you want to run the script with one of the other proxy containers, simply pass the name of the desired container. Example:

./build run base64-secret

Build the containers and run integration tests

This script is similar to run except it executes all the integration tests, which end up building and running additional proxy containers to simulate different scenarios.

./build tests

Use this script while developing new features.

Clean everything up

If you need to simply stop/delete all running Docker containers and remove their associated images, use this command:

./build clean

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Contributors

Check them out here.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

About

Lua script for Nginx that performs reverse proxy auth using JWT's

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 48.0%
  • Shell 22.5%
  • Lua 19.6%
  • Nginx 9.9%