Skip to content

Instantly share code, notes, and snippets.

@erseco
Last active September 22, 2023 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erseco/2b2a8c1e60d6baee4b39e147637a43d4 to your computer and use it in GitHub Desktop.
Save erseco/2b2a8c1e60d6baee4b39e147637a43d4 to your computer and use it in GitHub Desktop.
This script automates authentication for systems using Apereo CAS (Central Authentication Service). It logs in via command-line, useful for tasks/testing. More on Apereo CAS: github.com/apereo/cas
#!/bin/bash
# Usage: cas.sh {url} {username} {password}
# If you have any errors, try removing the redirects to get more information.
# Encode the destination URL using curl
DEST="${1}"
ENCODED_DEST=$(curl -Gso /dev/null -w %{url_effective} --data-urlencode "" "${DEST}" | cut -d'?' -f2)
# CAS server details
CAS_HOSTNAME="myidp.example.com"
# User credentials
USERNAME="${2}"
PASSWORD="${3}"
# Temporary files for cookies and headers
COOKIE_JAR=$(mktemp)
HEADER_DUMP_DEST=$(mktemp)
# Function to clean up temporary files
cleanup() {
rm -f "${COOKIE_JAR}" "${HEADER_DUMP_DEST}"
}
# Register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# Fetch the CAS login form and extract the CAS_ID
CAS_ID=$(curl --silent --location --cookie-jar "${COOKIE_JAR}" --url "https://${CAS_HOSTNAME}/cas/login?service=${ENCODED_DEST}" | sed -n 's/.*name="execution" value="\([^"]*\)".*/\1/p')
if [[ -z "${CAS_ID}" ]]; then
echo "Login ticket is empty."
exit 1
fi
# Submit the CAS login form
curl --silent --location --fail --data "username=${USERNAME}&password=${PASSWORD}&execution=${CAS_ID}&_eventId=submit" --cookie "${COOKIE_JAR}" --cookie-jar "${COOKIE_JAR}" --url "https://${CAS_HOSTNAME}/cas/login?service=${ENCODED_DEST}" --dump-header "${HEADER_DUMP_DEST}"
# Extract the redirection URL from the headers
CURL_DEST=$(grep Location "${HEADER_DUMP_DEST}" | sed 's/Location: //')
if [[ -z "${CURL_DEST}" ]]; then
echo "Cannot login. Check if you can login in a browser using user/pass = ${USERNAME}/${PASSWORD} and the following url: https://${CAS_HOSTNAME}/cas/login?service=${ENCODED_DEST}"
exit 1
fi
# Follow the redirection URL to get authenticated
curl --silent --location --fail --cookie "${COOKIE_JAR}" "${CURL_DEST}"
# Access the desired destination
curl --silent --location --fail --cookie "${COOKIE_JAR}" "${DEST}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment