How to set cookie in request header for REST service

10,816

this code is to authenticate an http request by using basic authentication, with some Username and Password

 byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" + password);
 string authToken = Convert.ToBase64String(credentialBuffer);
 string authHeaderValue = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Basic {0}", authToken);
 HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("https://TESTRestAPI/service/1/sub");
 request.Headers.Add(HttpRequestHeader.Authorization, authHeaderValue);

Additionaly, if it is required that the request contains some cookie with some name and some value, Id' use your code number 2.

 CookieContainer requestCookieContainer = new CookieContainer();
 Cookie requiredCookie = new Cookie("BasicAuth", "fromTest");
 requiredCookie.Domain = "https://TESTRestAPI/service/1/sub";
 requiredCookieContainer.Add(requiredCookie);
 request.CookieContainer = requestCookieContainer;

If your application runs on IIS, the config file may need some lines. I think basic authentication is disabled by default, as it isn't too much safe.

 <system.webServer>
    <security>
       <authentication>
          <basicAuthentication enabled="true"/>
       </authentication>
    </security>
  </system.webServer> 
Share:
10,816
user1532976
Author by

user1532976

Updated on June 04, 2022

Comments

  • user1532976
    user1532976 almost 2 years

    I am developing webservice which calls REST service and as per requirement I need to set cookie in the request header. EVen if I set everything , it gives me "401 Unauthorized message" as response.

     var request = (HttpWebRequest)HttpWebRequest.Create("https://TESTRestAPI/service/1/sub");
     request.Headers.Add("Authorization", "Basic" + Encoded);
     request.Method = "GET";
     request.ContentType = "application/json";
     var response = (WebResponse)request.GetResponse();
    
    So far I tried this :-
    1. request.Headers["Cookie"] = "BasicAuth=fromTest";
    2. request.CookieContainer = new CookieContainer();
       Uri target = new Uri("https://TESTRestAPI/service/1/sub"););
       Cookie ck = new Cookie("BasicAuth","fromTest") { Domain = target.Host };
    

    This is first time I am calling REST service, any help appreciated.