Skip to content

Instantly share code, notes, and snippets.

@eatnumber1
Last active July 28, 2023 21:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save eatnumber1/92e94086dafc7194077df4a6b45b2b75 to your computer and use it in GitHub Desktop.
Save eatnumber1/92e94086dafc7194077df4a6b45b2b75 to your computer and use it in GitHub Desktop.
Stateless Nginx Cookie Authentication
# Simple Cookie Authorization (SCA)
#
# SCA sets up an auth scheme which uses a secure cookie, presenting basic
# auth if the cookie isn't supplied.
#
# Put this file in /etc/nginx/conf.d
#
# To use it, put a stanza like the following in a server section:
#
# set $sca_realm "My Website";
# set $sca_token "my_secret_key";
# set $sca_token_max_age 7776000
# if ($cookie_sca_auth_token = $sca_token) {
# set $sca_auth_passed "yes";
# }
# auth_basic $sca_authorized_realm;
# auth_basic_user_file /etc/nginx/passwords/my_website;
# add_header Set-Cookie $sca_authorized_cookie;
#
# Tokens must not include commas, semicolons, or spaces.
map $sca_auth_passed $sca_authorized_realm {
"yes" "off";
default "$sca_realm";
}
# Don't send the cookie if the client already had it. This should allow the one
# already there to expire normally.
map $sca_authorized_realm $sca_authorized_cookie {
"off" "";
default "sca_auth_token=$sca_token; max-age=$sca_token_max_age; path=/; SameSite=strict; Secure; HttpOnly";
}
@lobstaj
Copy link

lobstaj commented May 29, 2023

Very nice, just what I needed!

Any particular reason you hard-coded the cookie's max-age?

@eatnumber1
Copy link
Author

No real reason I think. Should be fine to make it variable. Try it out, and if it works, send a pull request / report back?

@lobstaj
Copy link

lobstaj commented May 30, 2023

Seems to work with the parametrized max-age.

Apparently PR's aren't supported with gists, but here's the updated version in case you want to take a look / update yours: https://gist.github.com/lobstaj/adbb9e98cdd3f37f2bdce865ba95c603

@eatnumber1
Copy link
Author

Merged. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment