0

So, I was originally trying to create an item in a Sharepoint site, but as I took a 403 as response, and searched, I needed to put the X-RequestDigest header to work. I tried to fetch it using the "<site>/_api/contextinfo", but it comes back empty everytime I try. When I went to the Developer Tools in Chrome and tried the FormDigestValue there in my script, the item creation worked out fine. Can you help me out please? Thanks in advance for your help.

The PowerShell Script:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

#Install Sharepoint Module
If(-not(Get-InstalledModule SharePointPnPPowerShellOnline -ErrorAction silentlycontinue)){
    Write-Output "Will install SharePointPnPPowerShellOnline"
    Install-Module SharePointPnPPowerShellOnline -Confirm:$False -Force -Scope CurrentUser
}

#URLs
$baseUrl = "https://company.sharepoint.com"
$targetSite = "/sites/AprovacoesAutomaticasDev"
$formDigestUrl = "https://company.sharepoint.com/sites/AprovacoesAutomaticasDev/_api/contextinfo"


#Credentials
$username = "" #Empty for print reasons
$O365AdminPassword = ConvertTo-SecureString -String "" -AsPlainText -Force #Empty for print reasons
$CREDS = New-Object System.Management.Automation.PSCredential($username,$O365AdminPassword)

Write-Output "Connecting to source site"
Connect-PnPOnline -Url "$baseUrl$targetSite" -Credentials $CREDS -ErrorAction Stop

#Creating Context. Logging to Sharepoint.
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($baseUrl)
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$O365AdminPassword)
$Context.ExecuteQuery()   

Write-Output "Context Created"

#Setting WebSession
$AuthenticationCookie = $Context.Credentials.GetAuthenticationCookie($baseUrl, $true)
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$WebSession.Credentials = $Context.Credentials
$WebSession.Cookies.SetCookies($baseUrl, $AuthenticationCookie)
$WebSession.Headers.Add("Accept", "application/json;odata=verbose")
$WebSession.Headers.Add("Content-Type","application/json; odata=verbose")

#Testing
$Result = Invoke-RestMethod -Method Post -WebSession $WebSession  -Uri $formDigestUrl 

Out-File -FilePath .\result.json -InputObject $Result

The result:

d                           
-                           
@{GetContextWebInformation=}
1

You can use the below PowerShell code to read the form digest value:

Function Invoke-RestSPO(){
 
Param(
[Parameter(Mandatory=$True)]
[String]$Url,
 
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get,
 
[Parameter(Mandatory=$True)]
[String]$UserName,
 
[Parameter(Mandatory=$False)]
[String]$Password,
 
[Parameter(Mandatory=$False)]
[String]$Metadata,

[Parameter(Mandatory=$False)]
[System.Byte[]]$Body,
 
[Parameter(Mandatory=$False)]
[String]$RequestDigest,
 
[Parameter(Mandatory=$False)]
[String]$ETag,
 
[Parameter(Mandatory=$False)]
[String]$XHTTPMethod,

[Parameter(Mandatory=$False)]
[System.String]$Accept = "application/json;odata=verbose",

[Parameter(Mandatory=$False)]
[String]$ContentType = "application/json;odata=verbose",

[Parameter(Mandatory=$False)]
[Boolean]$BinaryStringResponseBody = $False

)
 
 
 
 
   if([string]::IsNullOrEmpty($Password)) {
      $SecurePassword = Read-Host -Prompt "Enter the password" -AsSecureString 
   }
   else {
      $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
   }
 
 
   $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
   $request = [System.Net.WebRequest]::Create($Url)
   $request.Credentials = $credentials
   $request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
   $request.ContentType = $ContentType
   $request.Accept = $Accept
   $request.Method=$Method
 
   if($RequestDigest) { 
      $request.Headers.Add("X-RequestDigest", $RequestDigest)
   }
   if($ETag) { 
      $request.Headers.Add("If-Match", $ETag)
   }
   if($XHTTPMethod) { 
      $request.Headers.Add("X-HTTP-Method", $XHTTPMethod)
   }
   if($Metadata -or $Body) {
      if($Metadata) {     
         $Body = [byte[]][char[]]$Metadata
      }      
      $request.ContentLength = $Body.Length 
      $stream = $request.GetRequestStream()
      $stream.Write($Body, 0, $Body.Length)
   }
   else {
      $request.ContentLength = 0
   }

   #Process Response
   $response = $request.GetResponse()
   try {
       if($BinaryStringResponseBody -eq $False) {    
           $streamReader = New-Object System.IO.StreamReader $response.GetResponseStream()
           try {
              $data=$streamReader.ReadToEnd()
              $results = $data | ConvertFrom-Json
              $results.d 
           }
           finally {
              $streamReader.Dispose()
           }
        }
        else {
           $dataStream = New-Object System.IO.MemoryStream
           try {
           Stream-CopyTo -Source $response.GetResponseStream() -Destination $dataStream
           $dataStream.ToArray()
           }
           finally {
              $dataStream.Dispose()
           } 
        }
    }
    finally {
        $response.Dispose()
    }
   
}
 
 
# Get Context Info 
Function Get-SPOContextInfo(){
 
Param(
[Parameter(Mandatory=$True)]
[String]$WebUrl,
 
[Parameter(Mandatory=$True)]
[String]$UserName,
 
[Parameter(Mandatory=$False)]
[String]$Password
)
 
   
   $Url = $WebUrl + "/_api/contextinfo"
   Invoke-RestSPO $Url Post $UserName $Password
}
 


Function Stream-CopyTo([System.IO.Stream]$Source, [System.IO.Stream]$Destination)
{
    $buffer = New-Object Byte[] 8192 
    $bytesRead = 0
    while (($bytesRead = $Source.Read($buffer, 0, $buffer.Length)) -gt 0)
    {
         $Destination.Write($buffer, 0, $bytesRead)
    }
}

Reference URL:

Consuming the SharePoint 2013 REST API from PowerShell

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.