Edit: to address the change in the question
I'm looking for what requests to make in what order - not implementation code
You can safely ignore the actual code implementation below - the order of the requests remains the same. In fact, exactly the same as in your original question.
If you're already making requests in the order that you've outlined, you needn't do anything more except provide an actual implementation. I'll leave the code in as an example, and so you can see exactly what order the requests need to be made in. I've stuck some numbering in to make it more obvious; the requests are denoted by 1, 2 & 3.
This is a basic PHP (i.e. non-Drupal) example...
First off make a generic function for sending your requests:
function send_request($url, array $post_array = array(), $cookie = NULL, $token = NULL) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'googlebot');
//curl_setopt($ch, CURLOPT_VERBOSE, $post_array);
if (!empty($post_array)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
}
if ($cookie) {
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
if ($token) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-CSRF-Token: ' . $token));
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
1. Then make your first call to log the user in:
// Login.
$data = array(
'username' => 'user',
'password' => 'password',
);
$result = send_request("http://server/endpoint/user/login.json", $data);
try {
$result = json_decode($result);
}
catch (Exception $e) {
die('Login failed: ' . $e->getMessage());
}
Next get the session name and ID, creating your cookie string to send with subsequent requests:
$session_id = $result->sessid;
$session_name = $result->session_name;
$cookie = $session_name . '=' . $session_id;
2. Then get a CSRF token, making sure to pass the cookie along:
$token = send_request("http://server/services/session/token", array(), $cookie);
3. Finally you can perform your request to the endpoint you're actually interested in. The cookie and token are injected by the send_request() function.
$user = array(
'mail' => '[email protected]',
'name' => 'name',
// Other relevant properties/fields.
);
$result = send_request('http://server/endpoint/user', $user, $cookie, $token);
I haven't tested the user creation endpoint so that might not be the exact structure it needs, but checking the responses for errors should let you know exactly what it's after quite quickly. I get the impression from your question that you're mainly interested in the steps leading up to that last request anyway.
The above is adapted from a basic test script I use, for a production environment you'll want to add more error/sanity checking in there. And the functionality is crying out to be wrapped in a class, and be extended to support PUT/DELETE, but I'll leave that to you :)