How to Serve Protected Content using X-Accel ( Nginx + Django )
In this blog I’ll show you my approach for solving the problem of serving protected content over the web server ( Only Authenticated user can download the files ).
There are other ways to solve this problem, like by buffering and streaming the content using the Back-end server, but this would put a heavy overhead over it ( like for example : 100 users try to download file of size 2Gb ).
Here I’ve used X-Accel redirect feature of Nginx to serve the protected content after it has been authenticated by the back-end logic.
Configuring Nginx :
X-accel allows for internal redirection to a location determined by a header returned from a back-end. This allows us to handle authentication in our back-end and then have Nginx handle serving the contents from redirected location to the end user, thus freeing up the back-end to handle other requests.
To configure X-accel redirection add internal keyword for the route which needs to be secured, like so.
location ^~ /download-logs {
alias /media/logs/;
internal;
}
Configuring Django API :
Here too we have multiple options to configure Django to serve re directions, such as using JWT, using separate secret key for file downloads requests, etc. I will show you my mechanism.
My solution’s flow: Whenever a user wants to download a log file, the user (UI) will first send a request for generating token, this token will be valid for 2 minutes. The user (UI) will then send another request with this secret token which is then used for validation and the API responds with X-accel redirection route from which user can download the file.
Django url :
url(r’^generate-media-token/$’, GenerateMediaAccessToken.as_view()),
url(r’^download-logs-with-token/$’, DownloadLogs.as_view(), name=’download-logs-token’),
Django views :
I’ve used this flow because the media access token is used in other places with restrictions otherwise JWT is a way better option.
And that’s it…. :)
Reach me out in comments if more details are needed.