Unable to authenticate in Sharepoint API on subsite using PHP

I’m trying to authenticate at a SharePoint Subsite, via PHP, in order to use the REST API and I’m getting some weird behavior.

I’m using the vgrem library.

This is the code I am using:

$authCtx = new AuthenticationContext($Settings['Url']);
$authCtx->acquireTokenForUser($Settings['UserName'],$Settings['Password']);

$ctx = new ClientContext($Settings['Url'],$authCtx);

The url has the following format:

https://sharepointSite.sharepoint.com/sites/SubSiteName/

The error I’m getting is:

External sharing is disabled for https://sharepointSite.sharepoint.com/

By the look of it the SharePoint site itself is not shared externally, but the subsite is.

I can authenticate via browser and execute some simple GET queries.

The library itself automatically tries to authenticate at:

https://sharepointSite.sharepoint.com/_forms/default.aspx?wa=wsignin1.0

I also tried to alter the library itself in order find the subsite auth page with no success. Some examples of what I tried:

https://sharepointSite.sharepoint.com/sites/SubSiteName/_forms/default.aspx?wa=wsignin1.0

https://sharepointSite.sharepoint.com/sites/_forms/default.aspx?wa=wsignin1.0

What I am currently trying with no success is to reproduce the auth done at the sharepoint site itself:

  1. Authenticate at https://login.microsoftonline.com/extSTS.srf (Success)
  2. The page is redirected to https://sharepointSite.sharepoint.com/{token}/login (Fails, cookies missing) It turns out this step wasn’t needed by the authentication process.
  3. https://sharepointSite.sharepoint.com/_forms/default.aspx (not reached yet)

I’m adding the cookies but it seems that something else happens on the backend or some cookie is missing.

I would be grateful if someone provides any help whatsoever. In the meantime I am going to keep on trying.

PS: I’ve searched most of the answers on SO, but they either refer to a different version of Sharepoint and library, or are obsolete (tried them, with no success).

EDIT: Step 2 was not needed in the end.

Answer

As it seems the problem was with the library itself. I solved the problem by adding the string

“&Source=/sites/SubSiteName/”

to the url. The line itself became:

//$subsite = "&Source=https://sharepointSite.sharepoint.com/sites/SubSiteName/"
$response = Requests::post($url.$subsite,null,$token, true, false);

inside the function acquireAuthenticationCookies($token). The extra false is a new variable added in order to apply the curl options only on the request in question.

Also I had to mess a little with the cookie settings, because the library was automatically discarding them on redirect. I had to add the following settings to the request:

curl_setopt($ch, CURLOPT_COOKIESESSION, false);
curl_setopt($ch, CURLOPT_COOKIEFILE, "");

EDIT: Forgot to put the file I edited. It as

php-spo/src/Runtime/Auth/SamlTokenProvider.php