使用c#登录需要Cookies的网站

Login to website which requires Cookies using c#

我正在尝试用 c# 编写一个脚本,能够从网站检索一些信息。这些信息受到保护,因此我需要先登录才能阅读它们。这就是我认为应该是我的程序:

我已经使用 Firefox 或 Chrome 的一些工具测试了 headers,但我不明白哪个是正确的程序。我注意到,如果我打开这个登录页面,我会收到一些 cookie。如果我删除这些 cookie 并尝试通过插入用户名和密码(通过浏览器)登录,我会收到一个错误作为网站的响应......它说我需要激活 cookie 才能登录。因此,当我第一次打开登录页面时,似乎收到了一些 cookie,然后我需要将它们与第一个 POST 登录请求一起发送。你们觉得有意义吗?

这是我现在使用的代码:

        string formUrl = "https://idp.kk-abcdefg.de/idp/Authn/UserPassword";
        string formParams = string.Format("j_username=MyUserName&j_password=MyPassword”);
        string cookieHeader;
        string pageSource;
        WebRequest req = WebRequest.Create(formUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        req.ContentLength = bytes.Length;
        using (Stream os = req.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        WebResponse resp = req.GetResponse();
        cookieHeader = resp.Headers["Set-cookie"];

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

而且我相信这是有效的,因为如果我使用正确的用户/密码或者我写错了,pageSource 的结果就会改变。但是当用户/密码正确时,我仍然无法登录,因为我收到以下错误消息:"This application requires cookies. Please make sure cookies are enabled in the settings of your browser. Please reload the login page and try logging in again".

这与我在浏览器中禁用 cookie 或删除首次加载登录页面时收到的 cookie 时遇到的错误相同。

你能帮我做这一切吗?我的想法是第一次打开登录页面时收到的cookie需要保存起来,然后连同下面的请求一起发送,但是我不知道该怎么做..

非常感谢!

在 Web 应用程序中,一旦用户成功登录,就会将一个 cookie 发送回浏览器以跟踪用户会话并确定用户在进一步请求期间是否登录。此外,您的应用程序的登录过程需要从客户端发送 cookie 以及用户名和密码。因此,当您尝试在没有浏览器的情况下执行登录时,它会抱怨缺少 cookie。

如果您知道需要发送哪些 cookie 及其值以及登录用户名和密码,您可以使用 WebRequest 中的 cookieContainer 发送它们,如下所示。

string formUrl = "https://idp.kk-abcdefg.de/idp/Authn/UserPassword";
string formParams = string.Format("j_username=MyUserName&j_password=MyPassword");

string cookieHeader;
string pageSource;

CookieContainer cookieContainer = new CookieContainer();
Cookie cookie1 = new Cookie("<<cookiename>>", "<<cookievalue>>","/", "<<yourdomainname>>");
Cookie cookie2 = new Cookie("<<cookiename>>", "<<cookievalue>>", "/", "<<yourdomainname>>");
cookieContainer.Add(cookie1);
cookieContainer.Add(cookie2);

// You can keep adding all required cookies this way.
var req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookieContainer;

req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

// You can access the cookies coming as part of response as following.
HttpWebResponse response = resp as HttpWebResponse;
if(response != null)
{
    var cookiesCollections = response.Cookies;
}

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

如果您不知道 cookie,并且需要在发布用户名和密码之前先请求登录页面来获取 cookie,然后使用以下方法。

var loginPageUrl = "<<Your Login Page url>>";
CookieContainer cookieContainer = new CookieContainer();
var req = (HttpWebRequest)WebRequest.Create(loginPageUrl);
req.CookieContainer = cookieContainer;
req.Method = "GET";

WebResponse resp = req.GetResponse();

HttpWebResponse response = resp as HttpWebResponse;

CookieCollection cookies;
if (response != null)
{
    cookies = response.Cookies; //Use this cookies in above code to send with username and password.
}

您发送请求登录两次并且使用单个 CookieContainer 对象