Last active
August 8, 2017 07:37
-
-
Save vgrem/658e3553befba9ed85b6 to your computer and use it in GitHub Desktop.
SharePoint Online HTTP handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Security; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.SharePoint.Client; | |
namespace SharePoint.Client | |
{ | |
public class SPHttpClientHandler : HttpClientHandler | |
{ | |
public SPHttpClientHandler(Uri webUri, string userName, string password) | |
{ | |
CookieContainer = GetAuthCookies(webUri, userName, password); | |
FormatType = FormatType.JsonVerbose; | |
} | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); | |
if (FormatType == FormatType.JsonVerbose) | |
{ | |
//request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json;odata=verbose")); | |
request.Headers.Add("Accept", "application/json;odata=verbose"); | |
} | |
return base.SendAsync(request, cancellationToken); | |
} | |
/// <summary> | |
/// Retrieve SPO Auth Cookies | |
/// </summary> | |
/// <param name="webUri"></param> | |
/// <param name="userName"></param> | |
/// <param name="password"></param> | |
/// <returns></returns> | |
private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password) | |
{ | |
var securePassword = new SecureString(); | |
foreach (var c in password) { securePassword.AppendChar(c); } | |
var credentials = new SharePointOnlineCredentials(userName, securePassword); | |
var authCookie = credentials.GetAuthenticationCookie(webUri); | |
var cookieContainer = new CookieContainer(); | |
cookieContainer.SetCookies(webUri, authCookie); | |
return cookieContainer; | |
} | |
public FormatType FormatType { get; set; } | |
} | |
public enum FormatType | |
{ | |
JsonVerbose, | |
Xml | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
would throw an error when call
GetAuthenticationCookie
as following: