Bash script example for custom services action with session authentication

Last updated on
30 April 2025

Here is Bash script example how to work with custom services action that requires session authentication.

Endpoint requirements :

  • Set "Authentication" as "Session authentication"
  • Set "Request parsing" to "application/x-www-form-urlencoded"
##
# Configurations.
##

# Base URL of your web site.
site_url="http://example.com"

# Endpoint URL for login action.
login_url="$site_url/service/path/user/login"

# Drupal authentication credentials.
password="YOURPASS"
username="YOURNAME"

# Path to temporary file which will store your cookie data.
cookie_path=/tmp/cookie

# URL of your custom action.
action_url="$site_url/service/path/custom/action"

# This is data that you want to send to your custom endpoint.
data="name=Alex&hobby=Drupal"

##
# Logic. Most likely you shouldn't change here anything.
##

# Get token and construct the cookie, save the returned token.
token=$(curl -b $cookie_path -c $cookie_path --request GET "$site_url/services/session/token" -s)

# Authentication. POST to $login_url with the token in header "X-CSRF-Token: $token".
curl -H "X-CSRF-Token: $token" -b $cookie_path -c $cookie_path -d "username=$username&password=$password" "$login_url" -s

# Get new token after authentication.
token=$(curl -b $cookie_path -c $cookie_path --request GET "$site_url/services/session/token" -s)

# Send POST to you custom action URL. With the token in header "X-CSRF-Token: $token"
curl -H "X-CSRF-Token: $token" -b $cookie_path -c $cookie_path -d "$data" "$action_url" -s

Help improve this page

Page status: Not set

You can: