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 Answer 1

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); 
2
  • No, that still gives me 401 Unauthorized. Do I need somehow actually set cookies? Commented Jul 27, 2013 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. Commented Jul 27, 2013 at 7:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.