Passing header authentication using PHP

Hi All,

Apologies for asking what seems to be a frequent question on these forums, but I’m struggling to resolve the 401 error “AUTH_REQUIRED” when sending any request after acquiring a session token.

I’ve browsed through the existing threads on the subject and tried all the different solutions, but none of them seem to be working for me.

Using the accounts endpoint as an example, here is my code in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.smarkets.com/v3/accounts/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Session-Token ' . $SessionID,
    'Accept: application/json',
    'Content-Type: application/json'
));

$APIResponse = json_decode(curl_exec($ch));

$HTTPStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

I’ve tried various ways of wrapping the session token, and also tried including it in the URL itself as a GET parameter, but I’m still receiving the same error message.

Is there anything special about the PHP cURL functions that requires the session ID to be passed differently?

I do have two-factor authentication enabled and have confirmed this is working when completing the verify stage of the login process (I tested it by deliberately entering an incorrect code, which returned an “INVALID_CREDENTIALS” error so I know this step is being completed). Additionally if I try going to that endpoint directly in a browser window while logged into my account, it returns the account information as expected so the problem is specifically in how I’m handling my PHP code.

Apologies if I’m missing something obvious here but I’m just not sure what else to try at this stage.

Hi All,

Finally figured out where I was going wrong, so I’m posting this here in case any future developers experience the same problem.

If your account is set up for two-factor authentication, then passing that authentication check generates a new token which is what is required for all future authentication headers.

In my case, although I was passing the two-factor authentication correctly, I wasn’t updating my $SessionID variable with the new token, which is why I was getting the “AUTH_REQUIRED” error every time.

Having corrected this, I can confirm the code snippet in my OP does indeed work and so if PHP is your language of choice, the above is a quick template you can use to get started.

I hope this is helpful.