Update CSOM PowerShell Scripts To Utilize Oauth

I have been scripting from longtime and as a result I have so many automations that are using Sharepoint CSOM, I only recently started utilizing PNP as new version of PNP utilized Oauth.

Reference: The way PnP PowerShell authenticates you to your tenant has changed. We now use OAuth behind the scenes to authenticate you. We support username/password auth, device code auth and app-only authentication.

It will work even if LegacyAuthProtocolsEnabled parameter is set to False as PNP(new version) use modern authentication mechanisms behind the scenes.

I am sure other might also be facing issues as well with CSOM when this parameter is False instead of True.

Set-SPOTenant -LegacyAuthProtocolsEnabled $false

Below error is received when LegacyAuthProtocolsEnabled is set to false:

Exception calling “ExecuteQuery” with “0” argument(s): “Cannot contact web site ‘https://techwizard.sharepoint.com/’ or the web site does not support SharePoint Online credentials. The response status code is ‘Unauthorized’. The response headers are ‘X-SharePointHealthScore=3, X-MSDAVEXT_Error=917656; Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically., SPRequestGuid=5246446a0-2000-1000-3d9f-577676823b5, request-id=5b4jk3bbja0-2018-2020-3d9f-584964763b5, MS-CV=oAZGUh567587tbVagjtQ.0, Strict-Transport-Security=max-age=31536000, SPRequestDuration=12, SPIisLatency=0, MicrosoftSharePointTeamServices=16.0.0.21910, X-Content-Type-Options=nosniff, X-MS-InvokeApp=1; RequireReadOnly, X-Cache=CONFIG_NOCACHE, X-MSEdge-Ref=Ref A: 5A879b1t78ntx187y148x7y87ybfhe886ADB Ref B: CH1EDGE1308 Ref C: 2021-11-24T13:52:40Z, Content-Length=0, Content-Type=text/plain; charset=utf-8, Date=Wed, 24 Nov 2021 13:52:39 GMT, P3P=CP=”ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI”, X-Powered-By=ASP.NET’.”

So now my task is to update the authentication code in the script while other code in the script should remain same, here is my code to get the client context:

$creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $pwd)

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)

$ctx.credentials = $creds

 

Here is what we need to do and replace this code with new code:

Install the PNP Powershell module

Install-Module -Name PnP.PowerShell

And connect to the admin URL for one time to apply permissions at tenant level (This will register the PNP app in your tenant)

Connect-PnPOnline -Url https://tenant-admin.sharepoint.com -Interactive


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Once the module is installed now you just need to replace the authentication code above with:

Connect-PnPOnline -Url $siteURL -Credentials $Credential

$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)

$ctx = Get-PnPContext

 

Also, you need to replace the code that you might have used for getting the list as shown below:

$listItems = $list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()

to

$ListItems = Get-PnPListItem -List $list

Example:

Previous code:

$lists = $ctx.web.Lists

$list = $lists.GetByTitle($lst)

$listItems = $list.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())

$ctx.load($listItems)

$ctx.executeQuery()

New Code:

$lists = $ctx.web.Lists

$list = $lists.GetByTitle($lst)

$ctx.load($list)

$ctx.executeQuery()

$ListItems = Get-PnPListItem -List $list

Note: Above is example only there might be some other basic changes required in your case instead whole script/code change.

After above change other parts of my lengthy script that updates the list item with status values and other status codes is working fine without changing them to set-pnplistitem,

You are all set now, no need to change the entire script with PNP cmdlets as PNP itself utilizes CSOM in the backend.

We just need to get the client context and some basic changes to our script to make it work again.

If you will check sign-in logs, it will now show client app as Mobile Apps and Desktop clients and application as PNP Management Shell.

Previous code was showing client app as other Clients (Other clients – Other protocols identified as utilizing legacy authentication)


 


You will now be able to fix your old scripts with just a minimal code update.

 

Thanks for reading …

Tech Wizard

https://techwizard.cloud

https://syscloudpro.com/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s