sparcopt
sparcopt

Reputation: 426

C# Log out HttpWebRequest

In my project I have a Login method that allows the user to use his email and password to log in into a specific website.

Everything works fine and the application is able to retrieve data from other pages wich require a user session.

I also want to give the user the option to log out. In order to do this, I went to see what was the action for the logout form. Example:

Final url: www.website.com/session/logout/

Then I use it in my HttpWebRequest...

        string formUrl = "www.website.com/session/logout/";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
        req.CookieContainer = Cookies; // using cookies from the log in request

        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        WebResponse resp = req.GetResponse();
        string cookieHeader = resp.Headers["Set-cookie"];

        using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        {
            string pageSource = sr.ReadToEnd();
        }

All seems to work fine but the pageSource returns this between all the code:

Error: Invalid form request: Due to security reasons and in order to protect your data each form can only be sent once and within a certain period of time. Do not use the back button of your browser to send forms again. You have to load a new form and to start the process anew.

I'm not sure what I'm missing. What I have to do here? What "you have to load a new form and start the process anew" means?

Upvotes: 0

Views: 903

Answers (1)

usr
usr

Reputation: 171178

This means that the website you are accessing is protecting its forms against CSRF. Probably, you must send a special token with the post request. Use Fiddler and use the website in a browser to see what the real form requires to have posted to it.

Upvotes: 1

Related Questions