Secure hash [http/authorization/secure_link_hash] ================================================= NGINX provides the ngx_http_secure_link_module to protect a web location from simple bots and web crawlers. In this example we will use JavaScript to generate the MD5 hash needed to implement a secure link. **Step 1:** Copy and paste the following commands to start your NGINX container with this lab's files: *Notice the SECRET_KEY environment variable* .. code-block:: shell EXAMPLE='http/authorization/secure_link_hash' docker run --rm --name njs_example -e SECRET_KEY=" mykey" -v $(pwd)/conf/$EXAMPLE.conf:/etc/nginx/nginx.conf:ro -v $(pwd)/njs/:/etc/nginx/njs/:ro -p 80:80 -d nginx **Step 2:** Now let's use curl to test our NGINX server: .. code-block:: shell :emphasize-lines: 1,4,7,10,13 curl http://127.0.0.1/secure/r 302 curl http://127.0.0.1/secure/r -L curl: (47) Maximum (50) redirects followed curl http://127.0.0.1/secure/r --cookie-jar cookie.txt 302 curl http://127.0.0.1/secure/r --cookie cookie.txt PASSED docker stop njs_example Code Snippets ~~~~~~~~~~~~~ This configuration rejects the first attempt to access the ``/secure/`` location by responding with a 302 redirect back to itself. Notice that along with the redirect a cookie is also set in the user's web client. The cookie contains an MD5 hash that is generated by our njs code. When the web client tries the request again, the cookie gets passed back to the server which NGINX then verifies to allow access. .. code-block:: nginx :linenos: :caption: nginx.conf env SECRET_KEY; ... http { js_path "/etc/nginx/njs/"; js_import main from http/authorization/secure_link_hash.js; js_set $new_foo main.create_secure_link; js_set $secret_key key main.secret_key; server { listen 80; ... location /secure/ { error_page 403 = @login; secure_link $cookie_foo; secure_link_md5 "$uri$secret_key"; if ($secure_link = "") { return 403; } proxy_pass http://localhost:8080; } location @login { add_header Set-Cookie "foo=$new_foo; Max-Age=60"; return 302 $request_uri; } } } This JavaScript uses the built-in crypto library to create an MD5 hash. Instead of hardcoding the encryption key into this file, we retrieve it from the SECRET_KEY environment variable. .. code-block:: js :linenos: :caption: secure_link_hash.js function secret_key(r) { return process.env.SECRET_KEY; } function create_secure_link(r) { return require('crypto').createHash('md5') .update(r.uri).update(process.env.SECRET_KEY) .digest('base64url'); } export default {secret_key, create_secure_link}