learning CORS & CSP with nginx

nginx setup

vhost setup

cd /etc/nginx/conf.d/
vi hostlocal.conf

server {
        listen 80;
        listen [::]:80;
        server_name hostlocal;
        http2 on;

        access_log /var/log/nginx/hostlocal.access.log;
        error_log  /var/log/nginx/hostlocal.error.log;

        location / {
                # w/o trailing slash (https://dev.to/danielkun/nginx-everything-about-proxypass-2ona)
                proxy_pass http://hostlocal:8080;

                # headers for backend api
                proxy_set_header host $http_host;
                proxy_set_header x-forwarded-for $http_x_forwarded_for;

                # headers for web client
                #add_header content-security-policy "default-src 'self'" always;
                add_header content-security-policy "default-src 'self' localhost:8080 lohostcal:8080" always;
                # img-src 'self' lohostcal
                # script-src 'self' localhost
        }

        ssi off;
        autoindex on;
        autoindex_exact_size off;
        location = /robots.txt          { access_log off; log_not_found off; }
        location = /favicon.ico         { access_log off; log_not_found off; }
        location ~ /apple-touch-icon    { access_log off; log_not_found off; }
}

web folder content

see test-cors-csp-contrib/

learning // acceptance

testing CORS

default behavior of the browser is correct: it does not download an external resource

frontend: http://hostlocal:8080
backend: http://localhost:8080

we should add the following header to the backend (ideally depending on the Origin specified in the request)

access-control-allow-origin: http://hostlocal:8080

and this is the only way to get access to the necessary resources

IMAGE HERE

testing CSP

browser’s default behavior is bad, it downloads any remote resource (possible XSS attack)

frontend: http://hostlocal (nginx)
backend: http://localhost:8080
images: http://lohostcal:8080

we need to add a header specifying the available resources (nginx example)

add_header content-security-policy "default-src 'self'" always;

only that way are hostile resources blocked

IMAGE HERE


HOME | GUIDES | LECTURES | LAB | SMTP HEALTH | HTML5 | CONTACT
Licensed under MIT