Search code examples
angularjsapinginxsails.jsrestrict

SailsJS as API and Nginx: Restrict external access


I'm running SailsJS on a digitalocean droplet (MEAN Stack with nginx). All my requests are mapped to my Angular frontend except those on /api which are mapped to a proxy_pass on port 1337 (on which Sails runs). This procedure works fine.

Now I'd like to restrict the access to my API to only allow requests from my frontend. I already tried to deny / allow from within my nginx config but this blocks the the user request itself. I tried several answers like this as well but they didn't work out.

What would be the recommended way to limit access to my Sails API to localhost? I'd like to run multiple apps on my droplet and use Sails as my API that should only be accessible by the apps in my droplet.

My nginx config:

upstream sails_server {
    server 127.0.0.1:1337;
    keepalive 64;
}

server {
    server_name domain.com;
    index index.html;

    location / {
        root /opt/domain/build;
        try_files $uri $uri/ /index.html;
    }

    location /api {
        proxy_http_version               1.1;
        proxy_set_header Connection      "";
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP       $remote_addr;
        client_max_body_size             500M;
    }
}

– Thanks in advance!


Solution

  • I think you can't do this because angular runs in your client, so you need to get IP from all you users. You can use something simple that works with trustes proxys

    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress

    or use some more complex and trusted like link