Forum Discussion
C# add a header, specifically Authorization header to SharePoint's ClientContext
Im tyring to connect to SharePoint rest API, I able to connect using Postman to connect but i can seem to figure out the C# side.
Does anyone know how i can add a header, specifically Authorization header to SharePoint's ClientContext?
Thank you
- SvenSieverdingBronze Contributor
A-Gon350
If you want to add additional headers to CSOM Clientcontext then you can modify the executing webrequest like described here "https://sharepointdragons.com/2012/04/20/authentication-when-using-the-sharepoint-client-object-model/"ClientContext clientContext = new ClientContext("http://thesitecollection"); clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs(clientContext_ExecutingWebRequest); Web site = clientContext.Web; clientContext.Load(site); clientContext.ExecuteQuery(); static void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e){ e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); }
But you might not need to go through all that hassle if you use Authenticationmanager from the PnP.Framework Library
https://github.com/pnp/pnpframework/blob/dev/src/lib/PnP.Framework/AuthenticationManager.cs
It gives you many authentication methods that just return a ClientContext object.AuthenticationManager auth = AuthenticationManager.CreateWithCredentials(username,password); ClientContext ctx = auth.GetContext(siteUrl);
- A-Gon350Copper Contributor
- SvenSieverdingBronze ContributorYes, i used
" <PackageReference Include="PnP.Framework" Version="1.10.0" />"
with netcoreapp3.1