Authentication for NginX

On my home server, I use NginX to serve some webapps and some static files. I wanted a global authentication mechanism that can work for all services. I decided to build mine directly in NginX.

The system is cookie based. A unique token is attributed to the user and stored in the cookie. A file named after the token is also created on the server. If the user doesn’t have the cookie set or if its value doesn’t point to a valid file, he is redirected to an authentication app.

The authentication app is a node JS app responsible for verifying login. A login form is submitted by the user. The username and the password are compared to a list stored in a small json file. If the informations match, the token is created and stored in the cookie and in the file. The user is then redirected to the location he wanted to reach. I also add a sign up form with activation. The app is based on the express framework, with the help of jade and stylus for the presentation.

Now, the NginX configuration :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    server {
        listen 80;
        server_name plonk.puyb.net plonk 192.168.0.254 localhost;

        location /auth/ {
            alias /srv/http/auth/;
            proxy_pass http://localhost:3000/;
            proxy_redirect default;
        }

        location / {
        if ($http_cookie ~* "AUTH_COOKIE=([a-z0-9]+)(?:/|$)") {
            set $auth_cookie $1;
        }

        if (!-f /var/lib/nginx/cookies/$auth_cookie) {
            rewrite ^ http://plonk.puyb.net/auth/?redirect=$request_uri break;
        }

        root /srv/http;
        index index.html index.php;
    }
}

The node JS app server run on port 3000.

The node JS app is on GitHub : Puyb/nginx-auth.

What can I improve ?
– This system lacks a mechanism to delete token files… How to do it ? I can simply delete files in a cron job a couple of hours after the creation date. But some users may be disconnected even if they are still using the system. The cookie is set only at login time. Unlike other cookie based systems, the cookie isn’t refreshed at each request. So if I set an expiration time, the session will expire a fixed amount of time after the login, even if the user is still active. I don’t have a solution yet… I’ll work on it later…

To log out, you just have to delete the cookie. You can do it in javascript :

1
document.cookie='AUTH_COOKIE=;expires=' + new Date().toGMTString()

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.