Skip to content

Instantly share code, notes, and snippets.

@kevinoconnor7
Last active March 17, 2024 15:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinoconnor7/76817712e35951f60b9e28810e4c6f93 to your computer and use it in GitHub Desktop.
Save kevinoconnor7/76817712e35951f60b9e28810e4c6f93 to your computer and use it in GitHub Desktop.
Home Assistant Command Line Authentication for Authelia
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
## BEGIN CONFIGURATION SECTION ##
# The domain/path of your authelia service. For example:
# - sso.example.com
# - example.com/auth
# - example.com:8443
#
# Do not include protocol or a trailing slash. Redirects will
# _not_ be followed.
# For safety we will force the request to be done over https.
AUTHELIA_DOMAIN="sso.example.com"
# The fully URL for your Home Assistant instance. This will
# be provided to Authelia for authoriziation purposes.
HOME_ASSISTANT_URL="https://home.example.com"
# Usernames should be validated using a regular expression to be of
# a known format. Special characters will be escaped anyway, but it is
# generally not recommended to allow more than necessary.
# This pattern is set by default. In your config file, you can either
# overwrite it with a different one or use "unset USERNAME_PATTERN" to
# disable validation completely.
USERNAME_PATTERN='^[a-z|A-Z|0-9|_|-|.]+$'
## END CONFIGURATION SECTION ##
# Log messages to stderr.
log() {
echo "$1" >&2
}
err=0
# Check username and password are present and not malformed.
if [ -z "$username" ] || [ -z "$password" ]; then
log "Need username and password environment variables."
err=1
elif [ ! -z "$USERNAME_PATTERN" ]; then
username_match=$(echo "$username" | sed -r "s/$USERNAME_PATTERN/x/")
if [ "$username_match" != "x" ]; then
log "Username '$username' has an invalid format."
err=1
fi
fi
[ $err -ne 0 ] && exit 2
status_code=$(curl --head --silent \
--request GET \
--header "X-Original-URL: https://${HOME_ASSISTANT_URL}" \
--basic --user "${username}:${password}" \
-o /dev/null \
-w '%{http_code}' \
"https://${AUTHELIA_DOMAIN}/api/verify?auth=basic")
# Auth success!
[ $status_code -eq 200 ] && exit 0
# Auth failed
exit 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment