Automating Drupal user login and maintaining session in curl

Automating Drupal user login and maintaining session in curl

Submitted by Jitesh Doshi on Thu, 04/04/2013 - 22:04
drupal logo

Using the services module in Drupal to expose CRUD operations on nodes is a great way to expose RESTful service from Drupal. All you have to do is to enable rest_server sub-module and create a REST server in it. Now you start fetching your nodes in XML, JSON or many other formats. Now for testing, the 'curl' command line browser was used to make HTTP requests in an automated fashion. Making read-only requests to fetch nodes as JSON was easy. Just run curl http://localhost/rest/node to get a list of nodes. But updating or creating nodes requires not just logging in, but also maintaining session across 'curl' requests.

That's where the --cookie-jar and --cookie options come in. Just login using

curl --cookie-jar cookie.txt "name=myusername&pass=mypassword&form_id=user_login" http://localhost/user/login

If login succeeds, this will save a session cookie in the cookie.txt file. Now you can use this cookie, and thus the session, with

curl --cookie cookie.txt http://localhost/some/path/that/needs/logged/in/session

and voila! Your command-line browser, curl, is interactive with Drupal as a logged in user!

But wait, there's more!

If you're not happy about having to put the actual password of the user in plain-text on the curl command-line above, the solution is to use Drush. With drush, you can generate a link that automatically logs you in, without providing the password. Just run

drush -l http://localhost user-login myusername

This will print a URL (that looks like http://localhost/user/reset/.../.../.../login) that you can paste into a browser and get logged in instantly. But instead of pasting it into a browser, you can pass it to curl - like this

curl --cookie-jar cookie.txt temporary-login-url

and that logs curl in without a password.  So the above two can be combined into ...

curl --cookie-jar cookie.txt `drush -l http://localhost user-login myusername`

(notice the reverse-quotes), and that saves a cookie in the cookie.txt file which can be used in subsequent curl requests with the --cookie option. That will make curl act as if it is logged in as myusername.

Jitesh Doshi

Profile picture for user Jitesh Doshi
Managing Partner & CTO
  • A seasoned technology entrepreneur and enthusiast
  • A regular speaker at industry conferences and universities
  • Host and organizer of technology user groups
  • Active in management of non-profit organizations serving the local community
  • Leader and contributor for multiple open-source projects
  • Expert in cloud, application integration, web and mobile technologies
  • Author of open-source projects, including on Drupal.org - Popular Tags and PRLP.
  • Developed several highly successful software platforms and frameworks for clients