• This repository has been archived on 14/Feb/2018
  • Stars
    star
    534
  • Rank 83,095 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

Contents

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

IMPORTANT: nginx-jwt is a Lua script that is designed to run on Nginx servers that have the HttpLuaModule installed. But ultimately its dependencies require components available in the OpenResty distribution of Nginx. Therefore, it is recommended that you use OpenResty as your Nginx server, and these instructions make that assumption.

Install steps:

  1. Download the latest archive package from releases.
  2. Extract the archive and deploy its contents to a 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;;";
        ...
    }

Configuration

At the moment, nginx-jwt only supports symmetric keys (alg = hs256), which is why you need to configure your server with the shared JWT secret below.

  1. 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;
  2. 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. Docker Toolbox
  2. Node.js

IMPORTANT: The test scripts expect your Docker Toolbox docker-machine VM name to be default

Ubuntu

  1. Docker
  2. Node.js

Besides being able to install Docker and run Docker directly in the host OS, the other different between Ubuntu (and more specifically Linux) and Mac OS is that all Docker commands need to be called using sudo. In the examples that follow, a helper script called build is used to perform all Docker commands and should therefore be prefixed with sudo, like this:

sudo ./build run

Ubuntu on MacOS (via Vagrant)

If your host OS is Mac OS but you'd like to test that the build scripts run on Ubuntu, you can use the provided Vagrant scripts to spin up an Ubuntu VM that has all the necessary tools installed.

First, if you haven't already, install Vagrant either by installing the package or using Homebrew.

Then in the repo directory, start the VM:

vagrant up

And then SSH into it:

vagrant ssh

Once in, you'll need to use git to clone this repo and cd into the project:

git clone THIS_REPO_URL
cd nginx-jwt

All other tools should be installed. And like with the Ubuntu host OS, you'll need to prefix all calls to the build script with sudo, like this:

sudo ./build run

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 and build 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 Docker Machine 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

Updating dependencies

It's always nice to keep dependencies up to date. This library (and the tools used to test it) has three sources of dependencies that should be maintained: Lua dependencies, test script Node.js dependencies, and updates to the proxy base Docker image.

Lua dependencies

These are the Lua scripts that this library uses. They are maintained in the build_deps.sh bash script.

Since these dependencies don't have any built-in versioning (like npm), we download a specific GitHub commit instead. We also check that a previously downloaded script is current by examining its SHA-1 digest hash. All this is done via the included load_dependency bash function.

If a Lua dependency needs to be updated, find its associated load_dependency function call and update its GitHub commit and sha1 parameter values. You can generate the required SHA-1 digest of a new script file using this command:

openssh sha1 NEW_SCRIPT

To add a new dependency simply add a new load_dependency command to the script.

Test script Node.js dependencies

All Node.js dependencies (npm packages) for tests are maintained in this package.json file and should be updated as needed using the npm command.

Proxy base Docker image

The proxy base Docker image may need to be updated periodically, usually to just rev the version of OpenResty that its using. This can be done by modifying the image's Dockerfile. Any change to this file will automatically result in new image builds when the build script is run.

Packaging

When a new version of the script needs to be released, the following should be done:

NOTE: These steps can only performed by GitHub users with commit access to the project.

  1. Increment the Semver version in the version.txt file as needed.
  2. Create a new git tag with the same version value (prefiexed with v):
git tag v$(cat version.txt)
  1. Push the tag to GitHub.
  2. Create a new GitHub release in releases that's associated with the above tag.
  3. Run the following command to create a release package archive and then upload it to the release created above:
./build package

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.

More Repositories

1

node-jsonwebtoken

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
JavaScript
17,054
star
2

java-jwt

Java implementation of JSON Web Token (JWT)
Java
5,403
star
3

express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes
TypeScript
4,396
star
4

jwt-decode

Decode JWT tokens; useful for browser applications.
JavaScript
2,913
star
5

angular2-jwt

Helper library for handling JWTs in Angular apps
TypeScript
2,606
star
6

nextjs-auth0

Next.js SDK for signing in with Auth0
TypeScript
2,009
star
7

angular-jwt

Library to help you work with JWTs on AngularJS
JavaScript
1,259
star
8

lock

Auth0's signin solution
JavaScript
1,121
star
9

go-jwt-middleware

A Middleware for Go Programming Language to check for JWTs on HTTP requests
Go
978
star
10

auth0.js

Auth0 headless browser sdk
JavaScript
949
star
11

auth0-spa-js

Auth0 authentication for Single Page Applications (SPA) with PKCE
TypeScript
900
star
12

auth0-react

Auth0 SDK for React Single Page Applications (SPA)
TypeScript
864
star
13

node-jwks-rsa

A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
JavaScript
824
star
14

node-jws

JSON Web Signatures
JavaScript
698
star
15

angular-storage

A storage library for AngularJS done right
JavaScript
644
star
16

repo-supervisor

Scan your code for security misconfiguration, search for passwords and secrets. 🔍
JavaScript
634
star
17

node-auth0

Node.js client library for the Auth0 platform.
JavaScript
586
star
18

cosmos

🔭 Auth0 Design System
JavaScript
545
star
19

JWTDecode.swift

A JWT decoder for iOS, macOS, tvOS, and watchOS
Swift
545
star
20

SimpleKeychain

A simple Keychain wrapper for iOS, macOS, tvOS, and watchOS
Swift
488
star
21

react-native-auth0

React Native toolkit for Auth0 API
TypeScript
477
star
22

express-openid-connect

An Express.js middleware to protect OpenID Connect web applications.
JavaScript
464
star
23

auth0-python

Auth0 SDK for Python
Python
445
star
24

JWTDecode.Android

A library to help you decode JWTs for Android
Java
437
star
25

docs

Auth0 documentation
JavaScript
366
star
26

auth0-PHP

PHP SDK for Auth0 Authentication and Management APIs.
PHP
355
star
27

wt-cli

Webtask CLI - all you need is code
JavaScript
322
star
28

auth0.net

.NET client for the Auth0 Authentication & Management APIs.
C#
296
star
29

passport-auth0

Auth0 authentication strategy for Passport.js
JavaScript
283
star
30

rules

Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0
JavaScript
283
star
31

react-native-lock

[DEPRECATED] A wrapper of Lock to use with React Native (iOS & Android)
Java
277
star
32

Auth0.swift

Auth0 SDK for Apple platforms
Swift
275
star
33

auth0-java

Java client library for the Auth0 platform
Java
265
star
34

Lock.swift

A Swift & iOS framework to authenticate using Auth0 and with a Native Look & Feel
Swift
251
star
35

auth0-cli

Build, manage and test your Auth0 integrations from the command line
Go
243
star
36

auth0-deploy-cli

The Auth0 Deploy CLI is a tool that helps you manage your Auth0 tenant configuration. It integrates into your development workflows as a standalone CLI or as a node module.
JavaScript
242
star
37

laravel-auth0

Laravel SDK for Auth0 Authentication and Management APIs.
PHP
224
star
38

Auth0.Android

Android toolkit for Auth0 API
Kotlin
213
star
39

jwks-rsa-java

Java
194
star
40

ruby-auth0

Ruby toolkit for Auth0 API
Ruby
189
star
41

cxn

cXn: extensible open-source CDN
Ruby
178
star
42

passport-windowsauth

Windows Authentication strategy for Passport.js
JavaScript
175
star
43

auth0-angular

Auth0 SDK for Angular Single Page Applications
TypeScript
175
star
44

terraform-provider-auth0

The Auth0 Terraform Provider is the official plugin for managing Auth0 tenant configuration through the Terraform tool.
Go
161
star
45

styleguide

🖌 Conjunction of design patterns, components and resources used across our products.
Stylus
160
star
46

jwt-handbook-samples

JWT Handbook code samples
JavaScript
143
star
47

Lock.Android

Android Library to authenticate using Auth0 and with a Native Look & Feel
Java
140
star
48

wordpress

WordPress Plugin for Auth0 Authentication
PHP
133
star
49

node-samlp

SAML Protocol support for node (only IdP for now)
JavaScript
129
star
50

go-auth0

Go SDK for the Auth0 Management API.
Go
122
star
51

passport-linkedin-oauth2

Passport Strategy for LinkedIn OAuth 2.0
JavaScript
115
star
52

omniauth-auth0

OmniAuth strategy to login with Auth0
Ruby
112
star
53

symfony

Symfony SDK for Auth0 Authentication and Management APIs.
PHP
110
star
54

node-odata-parser

OData query string parser for node.js.
JavaScript
106
star
55

node-jwa

JSON Web Algorithms
JavaScript
98
star
56

express-jwt-authz

Validate the JWT scope to authorize access to an endpoint
JavaScript
97
star
57

auth0-vue

Auth0 authentication SDK for Vue.js apps
TypeScript
95
star
58

lock-passwordless

Auth0 Lock Passwordless [DEPRECATED]
JavaScript
93
star
59

auth0-aspnetcore-authentication

SDK for integrating Auth0 in ASPNET Core
C#
93
star
60

node-oauth2-jwt-bearer

Monorepo for libraries that protect Node APIs with OAuth2 Bearer JWTs
TypeScript
88
star
61

open-source-template

A template for open source projects at Auth0
85
star
62

auth0-angular2

84
star
63

auth0-oidc-client-net

OIDC Client for .NET Desktop and Mobile applications
C#
84
star
64

auth0-authorization-extension

Auth0 Extension that adds authorization features to your account
JavaScript
82
star
65

react-browserify-spa-seed

Seed / Boilerplate project to create your own SPA using React, Browserify and ReworkCSS
JavaScript
80
star
66

node-baas

Node.js implementation of Bcrypt as a micro service.
JavaScript
79
star
67

password-sheriff

Password policies made easy.
JavaScript
77
star
68

idtoken-verifier

Lightweight RSA JWT verification
JavaScript
76
star
69

sharelock-android

Sharelock Android app
Java
76
star
70

auth0-spring-security-api

Spring Security integration with Auth0 to secure your API with JWTs
Java
76
star
71

ad-ldap-connector

Auth0 AD and LDAP connector
JavaScript
70
star
72

nodejs-msi

Build an MSI Windows Installer for a node.js application using WIX Toolset.
PowerShell
70
star
73

id-generator

Generates random ids with a prefix (a la Stripe)
JavaScript
66
star
74

node-saml

SAML assertion creation for node
JavaScript
65
star
75

webtask-scripts

JavaScript
61
star
76

TouchIDAuth

A library for passwordless authentication using TouchID & JWT
Objective-C
60
star
77

passport-azure-ad-oauth2

OAuth 2.0 authentication Passport strategies for Windows Azure Active Directory
JavaScript
59
star
78

spa-pkce

JavaScript
58
star
79

discourse-plugin

Discourse plugin to authenticate with auth0.
Ruby
58
star
80

auth0-flutter

Auth0 SDK for Flutter
Dart
58
star
81

auth0-multitenant-spa-api-sample

JQuery SPA + Node.js API with multi-tenant support
JavaScript
58
star
82

sandboxjs

Sandbox node.js code like a boss
JavaScript
58
star
83

multitenant-jwt-auth

This sample shows how to implement an API that authenticates using JWTs. It supports mutiple tenants and JWT blacklisting.
JavaScript
54
star
84

coreos-mongodb

CoreOS MongoDB units
52
star
85

shiny-auth0

Auth0 shiny proxy
JavaScript
51
star
86

auth0-cordova

Auth0 integration for Cordova apps
JavaScript
49
star
87

disyuntor

A circuit-breaker implementation for node.js
TypeScript
48
star
88

sharelock-osx

Swift
47
star
89

passport-wsfed-saml2

passport strategy for both WS-fed and SAML2 protocol
JavaScript
47
star
90

php-jwt-example

Php JWT example.
PHP
46
star
91

auth0-aspnet-owin

Auth0 ASP.NET 4.5 Owin/Katana Authentication Handler
JavaScript
46
star
92

webauthn.me

webauthn.me, learn more about the Web Authentication API or try the debugger.
JavaScript
46
star
93

auth0-dotnet-templates

Auth0 Templates for .NET
C#
44
star
94

auth0-java-mvc-common

Contains common helper classes and api client logic that are used across our Java MVC libraries
Java
43
star
95

auth0-custom-password-reset-hosted-page

An example on how to do a custom reset password hosted page.
HTML
41
star
96

express-oauth2-bearer

Experimental Middleware for express.js to validate access tokens.
JavaScript
40
star
97

magic

Auth0 Cryptography Toolkit
JavaScript
40
star
98

single-page-app-seed

A very opinionated seed for creating Single Page Apps that uses NO framework at all. Just a bunch of component libs
JavaScript
39
star
99

kbd

Styles for <kbd> tags.
HTML
37
star
100

webtask-workshop

36
star