Thursday, August 24, 2017

Sharing cookies for HttpWebRequest from Sharepoint site with FBA claims authentication

If you need to make sub request from your Sharepoint site you can do it like this (in this post we will assume that we make sub requests to the same Sharepoint site):

   1: var request = (HttpWebRequest)WebRequest.Create(url);
   2: request.Credentials = CredentialCache.DefaultNetworkCredentials;
   3: var response = (HttpWebResponse)request.GetResponse();

This code will work for Windows authentication – on receiver’s side if you will check SPContext.Current.Web.CurrentUser it will be the same as on sender’s side. But if the same code will run under FBA zone SPContext.Current.Web.CurrentUser will be null on receiver’s side. In order to force Sharepoint to execute the code under the same user also in FBA zone we need to share cookies:

   1: var request = (HttpWebRequest)WebRequest.Create(url);
   2: request.Credentials = CredentialCache.DefaultNetworkCredentials;
   3:  
   4: if (HttpContext.Current != null && web.Site.Zone != SPUrlZone.Default)
   5: {
   6:     HttpCookie authCookie = HttpContext.Current.Request.Cookies["FedAuth"];
   7:     if (authCookie != null)
   8:     {
   9:         log("Before send request: set auth cookies");
  10:         request.CookieContainer = new CookieContainer();
  11:         request.CookieContainer.Add(new Cookie("FedAuth", authCookie.Value,
  12:             authCookie.Path, new Uri(url).Host));
  13:     }
  14: }
  15:  
  16: var response = (HttpWebResponse)request.GetResponse();

In this example we assume that site works both with Windows and FBA zones and that Windows authentication is used on Default zone. After that SPContext.Current.Web.CurrentUser will be also correct on receiver’s side for FBA zone.

No comments:

Post a Comment