3

I have a page hosted in _layouts in SharePoint 2013. I want to make REST call to SharePoint REST api from this page using current user credentials. I don't want to do it from client-side (jquery etc)

So basically I want to make Web Request to the SharePoint REST api on the same server and pass current user authentication. I was able to do that in SharePoint 2010 by using default network credentials, but in 2013 it returns 401 Unauthorized.

Same thing with ClientContext. I cannot just do "new ClientContext(SPContext.Current.Web.Url)" Note: yes, there are Server APIs, but for things like Excel Services using REST API was just easier.

As I understand you need to pass access token for OAuth, but how do I get it for current user in SharePoint? Without making him reenter login/password and without using SharePoint Apps.

1

Claims Authentication uses an authentication cookie. You can create a 'cookie aware' WebClient that sets the cookies for the new request:

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}

You can make use of it as follows:

CookieAwareWebClient wc = new CookieAwareWebClient();
wc.UseDefaultCredentials = true;
string s = wc.DownloadString(url);
  • No, that still gives me 401 Unauthorized. Do I need somehow actually set cookies? – Voyta Jul 27 '13 at 5:59
  • I used that CookieAwareWebClient myself for calling a layout page from code behind. Didn't require additional logic or code. Of course the REST API might be different but don't have experience with that. – Steven Van de Craen Jul 27 '13 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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