Tuesday | 30 APR 2024
[ previous ]
[ next ]

nginx and Subrequest Authorization

Title:
Date: 2023-12-05
Tags:  nginx, sysadmin

As part of my quest to serving out media with nginx, I wanted to have some sort of authorization when static content was served. This is how I learned about the auth_request option in nginx where before you serve some content, you can trigger a subrequest to an authorization end point.

It's beautifully simple and I'm growing more and more fond of nginx. I already used it for everything but learning these features slowly is nice. Though after using it for this many years, you would think that I would know the tools I use.

server {
    listen 80;
    server_name example.com;
    
    location /videos {
        auth_request /auth;
        root /path/to/videos;
    }
    
    location /auth {
        add_header 'Access-Control-Allow-Origin' '*';
        proxy_pass https://backend/authorize;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    
    location / {
       root /path/to/example.com;
    }
}

The core idea is that the videos endpoint has an authorization request that get's run. It will forward the request to /auth where my backend can process the request and verify that it is a logged in user. If the request returns 200, then the videos endpoint will serve the content. If the request status is anything else then the user will not be served any content and will be given an error.

Quite handy!