Reusing Cookies for Automation

Previously I’ve wrote about using a Ruby script to automate fetching data from WP Engine’s portal. Recently that script broke due to the way WP Engine’s login process works. While it might be possible to fix, let’s look at bypassing the login process completely.

This involves using a real browser to login first then reusing those session cookies within a script.

The web server will simply see the script acting as a valid logged-in user. This allows the script to hit logged in pages without having to deal with the sign in process. Start by signing into the WP Engine portal with Google Chrome. Open up Chrome DevTools and navigate to the Application tab. On the left hand sidebar select Cookies and then https://my.wpengine. Next search for _session_id and current_account_id as shown here.

WP Engine _session_id shown with Chrome Devtools
WP Engine current_account_id shown with Chrome Devtools

Copy those values into a file named cookies.yaml with the following format. Place this file in the same folder as wpengine_portal.rb. Make sure these values are safe and not shared with anyone.

---
my.wpengine.com:
  "/":
    _session_id: !ruby/object:Mechanize::Cookie
      name: _session_id
      value: ##########################
      domain: my.wpengine.com
      path: "/"
      created_at: 2019-06-01 6:00:00.738014000 -04:00
      accessed_at: &2 2019-11-20 12:00:00.457749800 -05:00
    current_account_id: !ruby/object:Mechanize::Cookie
      name: current_account_id
      value: '##########################'
      domain: my.wpengine.com
      path: "/"
      created_at: &1 2019-11-20 12:00:00.457749800 -05:00
      accessed_at: *1

This file will be loaded up automatically when running wpengine_portal.rb from the command line. See instructions for using that script here.

Same process can be used for a wide range of automation tools.

While this short walk-through was specific to WP Engine and this particular Ruby script, the same process can be adapted for any website and scripting language. Cookie based authentication is quite commonplace. If you can log into with a browser, you most likely can start to automate something.