4

I have a problem in connecting to SharePoint online from the Windows 8.1 Application.

My goal is quite simple:

  • Connect to SharePoint

  • Retrieve the List of Lists

  • Get Items from a List

I have tried many and many way but I receive always the same "answer": 403 FORBIDDEN.

I'm Administrator on the SharePoint online Site Collection.

Here 2 examples of my code:

A) Trying to take the Auth Token

HttpClient hc = new HttpClient(new HttpClientHandler()
        {
             Credentials = new NetworkCredential("user@domain", "password"),
        });

hc.PostAsync(SharePointSite + "_api/contextinfo", new FormUrlEncodedContent(new List<KeyValuePair<string,string>>())).ContinueWith(
        postTask => 
        {
            var cnt = postTask.Result.Content;
            digest = cnt.ToString(); //FORBIDDEN!
            allDone.Set();
        });

        allDone.WaitOne();

        return digest;

B) Trying to access direct to the content

System.Net.Http.HttpClient _Client = new System.Net.Http.HttpClient(new HttpClientHandler()
            {
                   Credentials = new NetworkCredential(Username, Password, Domain),
            });
            _Client.BaseAddress = new Uri(SharePointSite);
            _Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(@"application/atom+xml"));
            //_Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _FormatBasicAuth(Domain, Username, Password));

            HttpResponseMessage resp = _Client.GetAsync(SharePointSite + "_api/web/lists").Result;
            string respString = resp.Content.ReadAsStringAsync().Result;

            if (resp.StatusCode==HttpStatusCode.OK){

            }

I read a lot, these are some interesting link

http://dlr2008.wordpress.com/2013/10/31/sharepoint-2013-rest-api-the-c-connection-part-1-using-system-net-http-httpclient/

http://msdn.microsoft.com/en-us/library/office/jj164022(v=office.15).aspx

2 Answers 2

5

Instead of a network credential, you will need a SharePoint Online Credential: http://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.client.sharepointonlinecredentials_members(v=office.15).aspx

1
  • Where do the username and password come from? Are they "regular" network credentials, or some special SharePoint Online credentials? I'm not the SharePoint admin, so I don't know if I need a special username and password set up in SharePoint Online before I begin.
    – neizan
    Aug 2, 2017 at 12:02
2

The following example demonstrates how to authenticate HttpClient in SharePoint Online:

public class SPHttpClientHandler : HttpClientHandler
{
    public SPHttpClientHandler(Uri webUri, string userName, string password)
    {
        CookieContainer = GetAuthCookies(webUri, userName, password);
        FormatType = FormatType.Json;
    }


    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        if(FormatType == FormatType.Json)
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        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
{
    Json,
    Xml
}

Gist: SPHttpClientHandler.cs

Prerequisites: SharePointOnlineCredentials class from SharePoint Online Client Components SDK is used for authentication.

Usage

 var handler = new SPHttpClientHandler(webUri, userName, password);
 using (var client = new HttpClient(handler))
 {
      client.BaseAddress = webUri;

      var result = client.GetAsync("/_api/web/lists").Result;
      var content = result.Content.ReadAsStringAsync().Result;
 }
1
  • Where do the username and password come from? Are they "regular" network credentials, or some special SharePoint Online credentials? I'm not the SharePoint admin, so I don't know if I need a special username and password set up in SharePoint Online before I begin.
    – neizan
    Aug 1, 2017 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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