401 in WebRequest from Azure Powershell Runbook to Sharepoint Online

Occasional Contributor

Hi.

 

This may be a long shot, but I am running into a weird issue. I have a powershell script, that basically creates a webrequest to https://[tenant].sharepoint.com/_api/contextinfo to get the FormDigestValue, that I use to make another webrequest towards the "/_layouts/groupstatus.aspx" page.

Now, this works perfectly, when running it locally, but when I run the script in an Azure Powershell Runbook, then it fails in the first webrequest, and gives me a 401 unauthorized.

I've tried different stuff, and the closest I could get to replicating it locally, was when I change the SharePointOnlineCredentials out with a normal PSCredentials. 

The script is as follows:

 

Add-Type –Path "[pathtofiles]\Microsoft.SharePoint.Client.dll" 
Add-Type –Path "[pathtofiles]\Microsoft.SharePoint.Client.Runtime.dll"

$Username = "***********"
$Password = "***********"
$pass = ConvertTo-SecureString $Password -AsPlainText -Force
$spcreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $pass)

$request = [System.Net.WebRequest]::Create("https://[tenant].sharepoint.com/_api/contextinfo/")
$request.Credentials = $spcreds
$request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
$request.Accept = "application/json;odata=verbose"
$request.Method="Post"
$request.ContentLength = 0
$response = $request.GetResponse()

 

 

I can't wrap my head around what the issue is. My thought is that it probably boils down to the credential part. I have made sure that the dll's are present and the most current dll's from Microsoft.

Or, could it be, that Azure is adding some headers to the webrequest, that Sharepoint does not allow?

 

Backgroundinfo:

I am basically trying to generate a call to the /_layouts/Groupstatus.aspx page, as I am trying to automate O365 group creation with templating on the Sharepoint site afterwards, and hitting that page with the newly created groupid, seems to be the best and quickest way to force the site creation. 

Any suggestions, alternatives or thoughts are also mighty appreciated.

 

Best Regards,

Uffe

4 Replies

are you seeing the validation attempts on the Sharepoint server ?

Also are you using powershell workflow runbooks, or regular runbooks ?

Also have you considered having a hybrid worker on prem to run the script

Hi Kent.

 

I am not seeing the validation attempts (actually, I don't know how, since it's SPO).

And I am using regular powershell runbooks, not the workflows.

Hi Kent. No, I haven't really considered using a hybrid worker on prem. I liked the idea about the workflow runbooks and wanted to see if I could use those, but I might consider alternatives.