0

I am developing an application that calls an endpoint, on which I have to authenticate to get cookie[connect. ssid] and use that cookie each I will be POSTing some data,
problem is I tried but with no success at all.

I manually login to that page and got the cookies manually and put in my request as below, and it worked.

The problem is that cookies expire after a couple of requests, my application will be deployed and that will be a huge problem.

I want that process to automatic,

  1. request cookies

  2. use it if still valid, if not request a new then proceed with the request

var url = "https:abcd";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Headers["Cookie"] = "connect.sid=s%3AhM62pU-YeAJFQxlNuFxYS76Fy8keCzbO.rECFaOPEiK%2FoVDzbMQjXyYlNsuT0UEew%2FWGlC4An%2FZY"; //value of the cookies
httpRequest.ContentType = "application/json";

using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
    streamWriter.Write(carrierjson);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
HttpStatusCode statusCode;
statusCode = httpResponse.StatusCode;
if (statusCode == HttpStatusCode.OK)
{
    //somecode here
}

I tried this

//REST API RestSharp but not working

var client = new RestClient("https://xxxxxxxxxxxxxx");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var body = @"{" + "\n" +
@"  ""username"": ""username""," + "\n" +
@"  ""password"": ""password""" + "\n" +
@"}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Stefan Wuebbe
  • 2,109
  • 5
  • 17
  • 28
  • How can you detect that the session has expired ? – Orace Jan 05 '23 at 12:28
  • Cookies are stored by the client or the browser doing the request. A lot of things can affect the response depending on what url is being hit, they might have additional security and checks on the http referrer for example. Not sure if these will help, but it might provide some points of interest. https://stackoverflow.com/questions/12024657/cookiecontainer-confusion https://learn.microsoft.com/en-us/dotnet/api/system.net.cookiecontainer?view=net-7.0 If this is your website, you might want to consider token authentication as well, such as OAuth/Bearer as a separate endpoint. – Netferret Jan 05 '23 at 12:31
  • cause at some point POSTING to that endpoint does not work if it's successful I check the status as followstatusCode == HttpStatusCode.OK each time it's not working, then I know the cookies have expired – Master Tesh Jan 05 '23 at 12:43

0 Answers0