Tuesday, June 4, 2019

Login to SharePoint CSOM with ADFS using PoweShell



cls
#Adding the Client OM Assemblies     
        Add-Type -Path "D:\SharePointClientDLL\Microsoft.SharePoint.Client.dll"
        Add-Type -Path "D:\SharePointClientDLL\Microsoft.SharePoint.Client.Runtime.dll"
function MixedAuthRequestMethod()
{
    param([Parameter(Mandatory=$true)][object]$clientContext)
    Add-Type -TypeDefinition @"
    using System;
    using Microsoft.SharePoint.Client;
    namespace SPCSOM.SPOHelpers
    {
        public static class ClientContextHelper
        {
            public static void AddRequestHandler(ClientContext context)
            {
                context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(RequestHandler);
            }
            private static void RequestHandler(object sender, WebRequestEventArgs e)
            {
                e.WebRequestExecutor.RequestHeaders.Remove("X-FORMS_BASED_AUTH_ACCEPTED");
                e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            }
        }
    }
"@
[SPCSOM.SPOHelpers.ClientContextHelper]::AddRequestHandler($clientContext);
}


$spurl = <SharePoint Portal URL>
$user = "< User Prefix>|<trustName>|<emailid>"
$pwd= "<Password>"
$secpass = ConvertTo-SecureString $pwd -AsPlainText -Force
$context = New-Object Microsoft.SharePoint.Client.ClientContext($spurl )
$context.AuthenticationMode = [Microsoft.SharePoint.Client.ClientAuthenticationMode]::Default
$credentials = New-Object System.Net.NetworkCredential($user , $secpass )
$context.Credentials = $credentials.$credentials
MixedAuthRequestMethod $context;

if (!$context.ServerObjectIsNull.Value) {
    Try
    {
        $spweb = $context.Web
        $context.Load($spweb )
        $context.ExecuteQuery()
        Write-Host $spweb .Title
         Write-Host $spweb .Url

    }
    Catch
    {
        Write-Host $_.Exception.Message
        Write-Host $_.Exception
        Write-Host "unable to connect" $spurl -ForegroundColor Red
    }
} else {
    Write-Host "Context object is null"
}

No comments:

Post a Comment