Search code examples
c#apihttphttpwebrequesthttpwebresponse

Not being able to get cookie from a redirect response


I'm trying to call an api auth method, which doesn't provide the session id in json, rather it redirects to some other page and provide the session id as cookie.

Here is what the site owner suggested me to do:

• Configure your client not to follow the redirect - just get the url • If it keeps you in the current page it means the login failed • If you are redirected to main/index, you are correctly authenticated, and you can keep the cookie for further requests

 var webRequest = (HttpWebRequest)WebRequest.Create("https:\\URL");
        webRequest.UserAgent =
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36";
        webRequest.Method = "POST";
        webRequest.Timeout = 60000;
        webRequest.AllowAutoRedirect = true;
        webRequest.CookieContainer = new CookieContainer();

        webRequest.ContentType = "application/x-www-form-urlencoded";

        webRequest.ContentLength = data.Length;

        using (var stream = webRequest.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)webRequest.GetResponse();
        var test = response.ResponseUri;

when I tried with AllowAutoRedirect as false, I didn't get the redirected url, but got the cookie. If I try with AllowAutoRedirect as true, then I'm getting the redirected url, but not getting the cookie. If I keep AllowAutoRedirect as false How can I be sure that the loging was successful and I got the correct session id as cookie?


Solution

  • I figured it out.

    If we set AllowAutoRedirect as false, then response will have an added header as location which will contain the redirected url. I got the redirected url in the location, in this kind of scenario the http response should be 302.