Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active August 1, 2021 13:11
Show Gist options
  • Save Integralist/e428e20a636b3a9ace3238d8412c7670 to your computer and use it in GitHub Desktop.
Save Integralist/e428e20a636b3a9ace3238d8412c7670 to your computer and use it in GitHub Desktop.
[Varnish VCL Basic Authentication] #security #basicauth #authentication #vcl #varnish #fastly #cdn

generate a username/password

echo -n beep:boop | base64

YmVlcDpib29w

Note: it's important to use -n otherwise echo will add a line break and that can be a time consuming error to debug when you find your username/password isn't working ;-) if you do find you need to debug, then use curl with the -v flag and inspect the request headers being sent and make sure your base64 encoded username/password matches what curl generates for the Authorization header when using the --user flag (see below curl examples)

vcl code

sub vcl_recv {
  #FASTLY recv
  
  if (!req.http.Authorization ~ "Basic YmVlcDpib29w") {
    error 401 "Restricted";
  }

  return(lookup);
}

sub vcl_error {
  #FASTLY error
  
  if (obj.status == 401) {
    set obj.http.Content-Type = "text/html; charset=utf-8";
    set obj.http.WWW-Authenticate = "Basic realm=Secured";

    synthetic {"
      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <title>Error</title>
        </head>
        <body>
          <h1>401 Unauthorized (varnish)</h1>
        </body>
      </html>
      "};

    return (deliver);
  }
}

example curl commands

curl --user beep:boop https://www.example.com/auth-me
curl -H "Authorization: Basic YmVlcDpib29w" https://www.example.com/auth-me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment