Authenticating HTTP request with Nginx

How to authenticate HTTP request with Nginx

Authgear has an internal endpoint that can authenticate HTTP request.

Prerequisite

You must follow this to get Authgear running first!

Create a simple application server

Below is a very simple application server written in Python that echoes most of the request headers.

from wsgiref.simple_server import make_server


def header_name(key):
    parts = key.split("_")[1:]
    parts = [part.lower() for part in parts]
    return "-".join(parts)


def app(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]
    start_response(status, headers)

    for key, value in environ.items():
        if key.startswith("HTTP_"):
            name = header_name(key)
            yield ("%s: %s\n" % (name, value)).encode()


with make_server('', 8000, app) as httpd:
    print("listening on port 8000...")
    httpd.serve_forever()

Run it with:

Visit http://localhost:8000 to verify it is working.

Make the application server a service in docker-compose.yaml

We have to write a Dockerfile for our application server.

We then declare it as a new service in docker-compose.yaml:

Finally, run it!

Visit http://localhost:8000 to verify our application server is working with docker-compose.

Add Nginx

Copy the following nginx.conf and save it as nginx.conf.

Note: When plain domain is used in proxy_pass directive, the domain is resolved once and then cached indefinite. If the domain is public, then you use use variable in proxy_pass with resolver directive to respect DNS TTL. See https://www.nginx.com/blog/dns-service-discovery-nginx-plus/ For instructions on how to setup Nginx for production deployment, see Using Nginx as the reverse proxy.

Add Nginx in docker-compose.yaml:

Visit http://localhost:8080 to reach Authgear and the application server.

Verify the request is authenticated

Visit http://localhost:8080 and login, then visit http://localhost:8080/app.

You should see the following:

Optional: setting up resolver response caching

Sometimes you may want to cache resolver response in nginx, for example, when the reverse proxy and Authgear is in different regions.

You may modify the nginx configuration as following to enable caching:

Last updated

Was this helpful?