Skip to content

Instantly share code, notes, and snippets.

@lizhiyong2000
Created October 16, 2019 05:37
Show Gist options
  • Save lizhiyong2000/30e6e75e23de4a04425e16553da3c350 to your computer and use it in GitHub Desktop.
Save lizhiyong2000/30e6e75e23de4a04425e16553da3c350 to your computer and use it in GitHub Desktop.
curl cas server login
# Usage: cas-get.sh {url} {username} {password} # If you have any errors try removing the redirects to get more information
# The service to be called, and a url-encoded version (the url encoding isn't perfect, if you're encoding complex stuff you may wish to replace with a different method)
DEST="$1"
ENCODED_DEST=`echo "$DEST" | perl -p -e 's/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg' | sed 's/%2E/./g' | sed 's/%0A//g'`
echo $ENCODED_DEST
#IP Addresses or hostnames are fine here
CAS_HOSTNAME=cas.test.com:9000
#Authentication details. This script only supports username/password login, but curl can handle certificate login if required
USERNAME=test
PASSWORD=12345678
#Temporary files used by curl to store cookies and http headers
COOKIE_JAR=.cookieJar
HEADER_DUMP_DEST=.headers
rm $COOKIE_JAR
rm $HEADER_DUMP_DEST
#The script itself is below
url=https://$CAS_HOSTNAME/login?service=$ENCODED_DEST
echo $url
#Visit CAS and get a login form. This includes a unique ID for the form, which we will store in CAS_ID and attach to our form submission. jsessionid cookie will be set here
test=`curl -s -k -c $COOKIE_JAR https://$CAS_HOSTNAME/login?service=$ENCODED_DEST`
echo $test
CAS_ID=`echo $test| grep -Po 'name="execution" value="\K[^"]+'`
echo $CAS_ID
#Submit the login form, using the cookies saved in the cookie jar and the form submission ID just extracted. We keep the headers from this request as the return value should be a 302 including a "ticket" param which we'll need in the next request
DATA="username=$USERNAME&password=$PASSWORD&execution=$CAS_ID&_eventId=submit&geolocation="
echo $DATA
curl -v -s -k -X POST --data $DATA -i -b $COOKIE_JAR -c $COOKIE_JAR https://$CAS_HOSTNAME/login?service=$ENCODED_DEST -D $HEADER_DUMP_DEST -o /dev/null
#Linux may not need this line but my response from the previous call has retrieving windows-style linebreaks in OSX
#dos2unix $HEADER_DUMP_DEST > /dev/null
#Visit the URL with the ticket param to finally set the casprivacy and, more importantly, MOD_AUTH_CAS cookie. Now we've got a MOD_AUTH_CAS cookie, anything we do in this session will pass straight through CAS
CURL_DEST=`grep Location $HEADER_DUMP_DEST | sed 's/Location: //'`
COOKIE=`grep "Set-Cookie: TGC" $HEADER_DUMP_DEST | grep -Po 'TGC=\K[^;]+'`
echo $COOKIE
echo ${#CURL_DEST}
CURL_DEST=${CURL_DEST%$'\r'}
curl -v -s -k -L -c $COOKIE_JAR -b "TGC=$COOKIE" "$CURL_DEST"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment