public void TestIsCookieForUrlWithSecureCookieSecureUrl() { Cookie cookie = new Cookie("subdir", "1", "/", "a.com") { Secure = true }; Assert.IsTrue(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("https://a.com/subdir"))); }
public void TestIsCookieForUrlWithPathCookieCorrectSubdirUrl() { Cookie cookie = new Cookie("subdir", "1", "/b", "a.com") { Secure = false }; Assert.IsTrue(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("http://a.com/b/c"))); }
public void TestNotIsCookieForUrlWithNotDottedCorrectSubdomain() { Cookie cookie = new Cookie("subdir", "1", "/", "a.com") { Secure = false }; Assert.IsFalse(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("http://b.a.com/"))); }
public void TestIsCookieForUrlWithDottedIncorrectSuffixedDomain() { Cookie cookie = new Cookie("subdir", "1", "/", ".a.com") { Secure = false }; Assert.IsFalse(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("http://ba.com/"))); }
public void TestIsCookieForUrlWithDottedCorrectDomainIgnorePort() { Cookie cookie = new Cookie("subdir", "1", "/", ".a.com") { Secure = false }; Assert.IsTrue(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("http://a.com:8080/"))); }
public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority) { authCookie = null; userName = null; password = null; authority = null; return(false); }
private System.Net.Cookie getCookie(System.Xml.XmlReader xtr) { bool isEnd = false; System.Net.Cookie cookie = new System.Net.Cookie(); string tagName = ""; string kind = ""; while (xtr.Read() && !isEnd) { switch (xtr.NodeType) { case System.Xml.XmlNodeType.Element: tagName = xtr.Name.ToLower(); break; case System.Xml.XmlNodeType.Text: switch (tagName) { case "key": kind = xtr.Value.ToLower(); break; case "real": case "string": case "date": switch (kind) { case "domain": cookie.Domain = xtr.Value; break; case "name": cookie.Name = xtr.Value; break; case "value": cookie.Value = xtr.Value; if (cookie.Value != null) { cookie.Value = Uri.EscapeDataString(cookie.Value); } break; case "expires": cookie.Expires = DateTime.Parse(xtr.Value); break; case "path": cookie.Path = xtr.Value; break; } break; } break; case System.Xml.XmlNodeType.EndElement: if (xtr.Name.ToLower() == "dict") { isEnd = true; } break; } } return cookie; }
public void TestNotIsCookieForUrlExpiredWithDottedCorrectDomain() { Cookie cookie = new Cookie("subdir", "1", "/", ".a.com") { Expiry = new DateTime(1), Secure = false }; Assert.IsFalse(ResourceFetcher.IsCookieForUrl_(cookie, new Uri("http://a.com/"))); }
public override bool Equals(Object comparand) { System.Net.Cookie c = comparand as System.Net.Cookie; return(c != null && String.Compare(this.name, c.name, true, CultureInfo.InvariantCulture) == 0 && String.Compare(this.val, c.val, false, CultureInfo.InvariantCulture) == 0 && String.Compare(this.Path, c.Path, false, CultureInfo.InvariantCulture) == 0 && String.Compare(this.domain, c.domain, true, CultureInfo.InvariantCulture) == 0 && this.version == c.version); }
public static JsonServiceClient authenticatedClient(int domain_id, string username, string password) { var jsonclient = new JsonServiceClient("https://" + url); jsonclient.StoreCookies = true; var response = jsonclient.Post<AuthenticationResponse>(new Authentication() { domain_id = domain_id, password = password, username = username }); var headers = jsonclient.Headers.AllKeys; var cookie = new System.Net.Cookie("ss-id", response.session_id, "/", url); jsonclient.CookieContainer.Add(cookie); return jsonclient; }
public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority) { //userName = _userName; //password = _password; //authority = _domain; //authCookie = new System.Net.Cookie(".ASPXAUTH", ".ASPXAUTH", "/", "Domain"); //return true; authCookie = null; userName = password = authority = null; return(false); }
public static System.Net.Cookie ToNetCookie(this HttpCookie cookie) { var netCookie = new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain) { Expires = cookie.Expires, HttpOnly = cookie.HttpOnly, Secure = cookie.Secure }; return(netCookie); }
// See par 3.6 of RFC 2616 static string QuotedString(System.Net.Cookie cookie, string value) { if (cookie.Version == 0 || IsToken(value)) { return(value); } else { return("\"" + value.Replace("\"", "\\\"") + "\""); } }
public bool GetFormsCredentials(out System.Net.Cookie authCoki, out string userName, out string password, out string authority) { userName = _userName; password = _password; authority = _domain; authCoki = new System.Net.Cookie(".ASPXAUTH", ".ASPXAUTH", "/", "Domain"); return(true); }
public async Task Get([FromQuery] InputContract input) { Logger.LogInformation($"Lade Daten von StudIP zu {input}"); string SessionCookie = await LoginActivityService.Login(input.Username, input.Password, input.Url); string path = "data"; var cookie = new Cookie("Seminar_Session", SessionCookie, "/", new Uri(StudIPClient.BASE).Host); var client = new StudIPClient(cookie, false); client.syncFiles(path); }
public System.Net.Cookie ToCookieObj() { System.Net.Cookie cookie = new System.Net.Cookie(Name, Value, Path, Domain); cookie.HttpOnly = HttpOnly; cookie.Secure = Secure; //Adding this sometimes returned an expired cookie date, resulting in the cookie being expired //and therefore not being used, even if it is working otherwise. //cookie.Expires = DateTimeOffset.FromUnixTimeSeconds((long) Expires).DateTime; return(cookie); }
private void getUserSession(ICookieGetter cookieGetter) { System.Net.Cookie cookie = cookieGetter.GetCookie(new Uri("http://nicovideo.jp/"), "user_session"); if (cookie != null) { txtUserSession.Text = cookie.Value; } else { txtUserSession.Clear(); } }
public static bool IsCookieValid(string cookieString) { var cookieCollection = new CookieCollection(); var cookie = new System.Net.Cookie(); cookie.Name = "do_not_remove_this_0w0"; cookie.Path = "/"; cookie.Domain = ".inso.link"; cookie.Value = cookieString; cookieCollection.Add(cookie); return(IsCookieValid(cookieCollection)); }
//private string _UserName; //private string _PassWord; //private string _DomainName; //public CustomReportCredentials() //{ // _UserName = "******"; // _PassWord = "******"; // _DomainName = "g2partnersllc.local"; //} public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority) { //authCookie = null; //userName = "******"; //password = "******"; //authority = "Admin"; //???? //return false; // not use FormsCredentials unless you have implements a custom autentication. authCookie = null; userName = password = authority = null; return(false); }
internal static void SetCookie(string cookieString) { var cookieCollection = new CookieCollection(); var cookie = new System.Net.Cookie(); cookie.Name = "do_not_remove_this_0w0"; cookie.Path = "/"; cookie.Domain = ".inso.link"; cookie.Value = cookieString; cookieCollection.Add(cookie); SetCookie(cookieCollection); }
public void AddCookie(System.Net.Cookie cookieToAdd) { var cookieValue = Uri.UnescapeDataString(cookieToAdd.Value); Cookie updatedCookie = new ReturnedCookie( cookieToAdd.Name, cookieValue, cookieToAdd.Domain, cookieToAdd.Path, cookieToAdd.Expires == default ? null : (DateTime?)cookieToAdd.Expires, cookieToAdd.Secure, cookieToAdd.HttpOnly); WrappedDriver.Manage().Cookies.AddCookie(updatedCookie); }
/// <summary> /// /// </summary> /// <param name="cookies"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static System.Net.Cookie AddOrSet(this System.Net.CookieCollection cookies, string name, string value) { var c = cookies[name]; if (c != null) { c.Value = value; return(c); } var r = new System.Net.Cookie(name, value); cookies.Add(r); return(r); }
// Функция чтобы получить куки для обычного HttpRequest или моего SimpleBrowser - проблема в том что на сайте посольства очень интересная проверка на подленость юзера public void GetCookiesFromDrive() { using (var Driver = new ChromeDriver()) { Globals.IdService = 1; Globals.IdCity = 92; Driver.Manage().Window.Maximize(); Driver.Navigate().GoToUrl("https://secure.e-konsulat.gov.pl/Uslugi/RejestracjaTerminu.aspx?IDUSLUGI=" + Globals.IdService + "&IDPlacowki=" + Globals.IdCity); if (Globals.IsElementDisplayed(Driver, By.Id("cp_KomponentObrazkowy_CaptchaImageID"))) { var cookies = Driver.Manage().Cookies.AllCookies; StreamWriter streamWriter = new StreamWriter(@"Cookies\" + Globals.cookieFileNameGuid + ".txt"); foreach (var result in cookies) { var cookieExpires = result.Expiry; var cookieDomain = result.Domain; var cookiePath = result.Path; var cookieName = result.Name; var cookieValue = result.Value; var cookieString = cookieName + ";" + cookieValue + ";" + cookiePath + ";" + cookieDomain + ";" + cookieExpires; streamWriter.WriteLine(cookieString); Console.WriteLine(cookieString); Cookie cookieNew = new Cookie(cookieName, cookieValue, cookiePath, cookieDomain); if (cookieExpires != null) { cookieNew.Expires = (DateTime)cookieExpires; } CapthaBrowser.Cookies.Add(cookieNew); } streamWriter.Close(); Driver.Close(); MessageBox.Show("Cookies has been saved!"); } else { MessageBox.Show("Error!"); Driver.Close(); } } }
/// <summary> /// Sets the authentication cookie of the specified request. /// </summary> /// <param name="request">The request to set the cookie for.</param> /// <param name="authenticationCookie">(Optional) The cookie to add to the request, if not specified defaults /// to the cookie of the user currently logged into the site.</param> public static void SetAuthenticationCookie(this HttpWebRequest request, Cookie authenticationCookie = null) { if (authenticationCookie == null) { //add the current authentication cookie to the request var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; authenticationCookie = new System.Net.Cookie ( FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, FormsAuthentication.CookieDomain ); } request.CookieContainer = new System.Net.CookieContainer(); request.CookieContainer.Add(authenticationCookie); }
public List <System.Net.Cookie> GetAllCookies() { List <Cookie> cookies = this.Driver.Manage().Cookies.AllCookies.ToList(); List <System.Net.Cookie> cookiesNet = new List <System.Net.Cookie>(); foreach (Cookie cookie in cookies) { System.Net.Cookie cookieNet = new System.Net.Cookie(); cookieNet.Name = cookie.Name; cookieNet.Value = cookie.Value; cookieNet.Domain = cookie.Domain; cookieNet.Path = cookie.Path; cookiesNet.Add(cookieNet); } return(cookiesNet); }
} // GetWebRequest /// <summary> /// Overriding the method defined in the base class. /// </summary> /// <param name="request"></param> /// <returns></returns> protected override System.Net.WebResponse GetWebResponse(System.Net.WebRequest request) { System.Net.WebResponse response = base.GetWebResponse(request); // http://social.msdn.microsoft.com/Forums/sqlserver/en-US/f68c3f2f-c498-4566-8ba4-ffd5070b8f7f/problem-with-ssrs-forms-authentication string cookieName = response.Headers["RSAuthenticationHeader"]; if (cookieName != null) { m_authCookieName = cookieName; System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)response; System.Net.Cookie authCookie = webResponse.Cookies[cookieName]; // save it for future reference and use. m_authCookie = authCookie; } return(response); } // GetWebResponse
public T ProcessRequest(string token, string logOn, string password, System.Net.Cookie cookie) { Uri uri = ToUrl(token); System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); wr.Credentials = new System.Net.NetworkCredential(logOn, password); wr.CookieContainer = new System.Net.CookieContainer(); if (cookie != null) { var cookiUri = cookie.Domain != null ? new Uri(cookie.Domain) : BaseUrl; wr.CookieContainer.SetCookies(uri, cookie.ToString()); } OnProcessingRequest(wr); #if !PORTABLE using (var response = wr.GetResponse()) using (var stream = response.GetResponseStream()) #else using (var stream = wr.GetRequestStreamAsync().Result) #endif { if (stream == null) { throw new InvalidOperationException("Response stream is null"); } var sr = new System.IO.StreamReader(stream); var jsonResult = sr.ReadToEnd(); var result = JsonParser.ParseJsonResult(jsonResult); if (result != null && result.CacheId != 0) { _cacheId = result.CacheId; } var ret = new T { Result = result }; OnProcessedRequest(ret); return(ret); } }
public static async Task Login(IHttpContext context) { Dictionary <string, string> payload = Server.Payload(context); string name = payload["name"]; string password = payload["password"]; string guid = Server.CheckCredentials(name, password); int prio = 1; string titel = "Login fehlgeschlagen"; string text = "Benutzername und Passwort prüfen.<br/>Neue Benutzer müssen freigeschaltet sein.<br/>" + @"<a href='/' class='w3-bar-item w3-button w3-teal w3-margin'>Nochmal</a>"; if (guid.Length > 0) { prio = 3; titel = "Login "; string level = "Beobachter"; System.Net.Cookie cookie = new System.Net.Cookie("MelBoxId", guid, "/"); context.Response.Cookies.Add(cookie); if (Server.LogedInHash.TryGetValue(guid, out Contact user)) { if (user.Accesslevel >= Server.Level_Admin) { level = "Admin"; } else if (user.Accesslevel >= Server.Level_Reciever) { level = "Benutzer"; } } text = $"Willkommen {level} {name}"; MelBoxSql.Tab_Log.Insert(Tab_Log.Topic.Web, 3, $"Login {level} >{name}<"); } string alert = Html.Alert(prio, titel, text); await Server.PageAsync(context, titel, alert); }
/// <summary> /// �N�b�L�[�w�b�_�[���N�b�L�[�ɕϊ����� /// </summary> /// <param name="header"></param> /// <returns></returns> private System.Net.Cookie ParseCookie(string header) { if (string.IsNullOrEmpty(header)) { throw new ArgumentException("header"); } System.Net.Cookie cookie = new System.Net.Cookie(); bool isCookieHeader = false; foreach (string segment in header.Split(new string[]{";"}, StringSplitOptions.RemoveEmptyEntries)) { KeyValuePair<string, string> kvp = ParseKeyValuePair(segment.Trim()); if (string.IsNullOrEmpty(kvp.Key)) { isCookieHeader = false; break; } switch (kvp.Key) { case "domain": cookie.Domain = kvp.Value; isCookieHeader = true; break; case "expires": cookie.Expires = DateTime.Parse(kvp.Value); break; case "path": cookie.Path = kvp.Value; break; default: cookie.Name = kvp.Key; cookie.Value = kvp.Value; if (cookie.Value != null) { cookie.Value = Uri.EscapeDataString(cookie.Value); } break; } } if (isCookieHeader) { return cookie; } else { return null; } }
/// <summary> /// Sets the cookie. /// </summary> /// <param name="cookie">The cookie.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentException">The cookie already exists.</exception> public void SetCookie(System.Net.Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (_cookies != null) { if (FindCookie(cookie)) { throw new ArgumentException("The cookie already exists."); } } else { _cookies = new CookieCollection(); } _cookies.Add(cookie); }
protected override System.Net.Cookie DataToCookie(object[] data) { System.Net.Cookie cookie = new System.Net.Cookie(); cookie.Value = data[0] as string; cookie.Name = data[1] as string; cookie.Domain = data[2] as string; cookie.Path = data[3] as string; if (cookie.Value != null) { cookie.Value = Uri.EscapeDataString(cookie.Value); } try { long exp = (long)data[4]; cookie.Expires = Utility.UnixTimeToDateTime((int)exp); } catch (Exception ex) { throw new CookieGetterException("firefoxのexpires変換に失敗しました", ex); } return cookie; }
private Task OnAddCookieRequested(System.Net.Cookie cookie) { if (Control == null || cookie == null || String.IsNullOrEmpty(cookie.Domain) || String.IsNullOrEmpty(cookie.Name)) { return(Task.FromResult <object>(null)); } var nsCookie = new NSHttpCookie(cookie); NSHttpCookieStorage.SharedStorage.SetCookie(nsCookie); if (!_cookieDomains.ContainsKey(cookie.Domain)) { _cookieDomains[cookie.Domain] = 0; } _cookieDomains[cookie.Domain] = _cookieDomains[cookie.Domain] + 1; #if DEBUG OnPrintCookiesRequested(); #endif return(Task.FromResult <object>(null)); }
public static List <System.Net.Cookie> GetCookie(this IWebDriver webdirver) { StopPageLoading(webdirver); var cookiesOnSelenium = webdirver.Manage().Cookies.AllCookies; List <System.Net.Cookie> cookies = new List <System.Net.Cookie>(); foreach (var ck in cookiesOnSelenium) { System.Net.Cookie cookie = new System.Net.Cookie(); cookie.Domain = ck.Domain; cookie.Name = ck.Name; cookie.Value = ck.Value; cookie.HttpOnly = ck.IsHttpOnly; cookie.Expires = ck.Expiry ?? DateTime.Now; cookie.Expired = ck.Expiry == default(DateTime) ? true : ck.Expiry < DateTime.Now; cookie.Path = ck.Path; cookies.Add(cookie); } return(cookies); }
public void SetGetDeleteCookies() { Manager.LaunchNewBrowser(); // Let's create a new cookie for a url. System.Net.Cookie c = new System.Net.Cookie("WebAii", "Rocks", "/", "http://www.webaii.com"); c.Expires = DateTime.Now.AddHours(1); ActiveBrowser.Cookies.SetCookie(c); // Query the cookie System.Net.CookieCollection siteCookies = ActiveBrowser.Cookies.GetCookies("http://www.webaii.com"); Assert.AreEqual(1, siteCookies.Count); Log.WriteLine(siteCookies[0].Name + ":" + siteCookies[0].Value + ":" + siteCookies[0].Domain); siteCookies[0].Domain = @"http://www.webaii.com"; // Now delete the cookie. ActiveBrowser.Cookies.DeleteCookie(siteCookies[0]); Assert.AreEqual(0, ActiveBrowser.Cookies.GetCookies("http://www.webaii.com").Count); }
/// <summary> /// win32apiを使って対象URL上の名前がKeyであるクッキーを取得します /// </summary> /// <param name="url"></param> /// <param name="key"></param> /// <returns></returns> protected override List<System.Net.Cookie> GetCookiesWinApi(Uri url, string key) { var cookies = new List<System.Net.Cookie>(); var lpszCookieData = PrivateGetCookiesWinApi(url, key); if(lpszCookieData.Length != 0) { Debug.WriteLine(lpszCookieData); string[] cookieDatas = lpszCookieData.ToString().Split(';'); foreach(var data in cookieDatas) { System.Net.Cookie cookie = new System.Net.Cookie(); string[] chunks = data.ToString().Split('='); if(2 <= chunks.Length) { try { cookie.Name = chunks[0].Trim(); cookie.Value = chunks[1].Trim(); cookie.Domain = AddDotDomain(url.Host); cookie.Path = url.Segments[0]; // このほうがいいきがする 2011-11-19 // cookie.Path = url.AbsolutePath; cookie.Expires = DateTime.Now.AddDays(30); // 有効期限適当付与 2013-07-03 cookies.Add(cookie); } catch(System.Net.CookieException e) { Debug.WriteLine(e.Message); } } } } return cookies; }
internal System.Net.Cookie ToCookie() { var cookie = new System.Net.Cookie( this.Name, this.Value, this.Path, this.Domain); return cookie; }
private async Task<HttpResponseMessage> GetPageEntity(string id = "", string asset = "") //hacky i kno { var url = asset; if (id != "") { url = RootUrl + id; } else { id = "ASSET"; } using (var handler = new HttpClientHandler()) { handler.CookieContainer = new System.Net.CookieContainer(); handler.UseCookies = true; handler.AllowAutoRedirect = true; var agecookie = new System.Net.Cookie("age_gate", "legal", "/", "www.thedrinkshop.com"); agecookie.Expires = DateTime.Now.AddYears(1); var sessioncookie = new System.Net.Cookie("PHPSESSID", "uf5mf0n7o4m2ldui2rrual7tt6", "/", "www.thedrinkshop.com"); handler.CookieContainer.Add(agecookie); handler.CookieContainer.Add(sessioncookie); using (var ht = new HttpClient()) { ht.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"); HttpResponseMessage r = new HttpResponseMessage(); var retryCounter = 0; Exception exHolder = new Exception(); while (r.Content == null && retryCounter < 10) { try { r = await ht.GetAsync(url); } catch(Exception ex) { exHolder = ex; retryCounter += 1; await Task.Delay(1000); } } if (r.Content == null) { throw exHolder; } //Debug.Write("HttpCode: " + r.StatusCode + " on page: " + id.ToString()); return r; } } }
/// <summary> /// 指定されたファイルからクッキーを取得する /// </summary> /// <param name="filePath"></param> /// <returns></returns> private System.Net.Cookie[] PickCookiesFromFile(string filePath) { List<System.Net.Cookie> results = new List<System.Net.Cookie>(); try { string data = System.IO.File.ReadAllText(filePath, Encoding.GetEncoding("Shift_JIS")); string[] blocks = data.Split('*'); foreach (string block in blocks) { string[] lines = block.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (7 < lines.Length) { System.Net.Cookie cookie = new System.Net.Cookie(); Uri uri = new Uri("http://" + lines[2]); cookie.Name = lines[0]; cookie.Value = lines[1]; cookie.Domain = uri.Host; cookie.Path = uri.AbsolutePath; // ドメインの最初に.をつける if (!cookie.Domain.StartsWith("www") && !cookie.Domain.StartsWith(".")) { cookie.Domain = '.' + cookie.Domain; } // 有効期限を取得する long uexp = 0, lexp = 0; if (long.TryParse(lines[6], out lexp) && long.TryParse(lines[7], out uexp)) { cookie.Expires = FileTimeToDateTime(lexp, uexp); } results.Add(cookie); } } } catch (Exception ex) { throw new CookieGetterException("IEクッキーの解析に失敗しました。", ex); } return results.ToArray(); }
/// <summary> /// Get a cookie from the browser /// </summary> /// <param name="name">The name of the cookie</param> /// <returns>The cookie (if exists)</returns> public override Cookie GetCookie(string name) { var localDriver = this.driver.Value; var cookieContainer = localDriver.Manage().Cookies; var seleniumCookie = cookieContainer.GetCookieNamed(name); if (seleniumCookie != null) { var cookie = new Cookie() { Name = seleniumCookie.Name, Domain = seleniumCookie.Domain, HttpOnly = seleniumCookie.IsHttpOnly, Expires = seleniumCookie.Expiry.GetValueOrDefault(), Path = seleniumCookie.Path, Value = seleniumCookie.Value, Secure = seleniumCookie.Secure }; return cookie; } else { return null; } }
protected override System.Net.Cookie DataToCookie(object[] data) { System.Net.Cookie cookie = new System.Net.Cookie(); string value = data[0] as string; // なんというめちゃくちゃな // chrome cookie version 7 if(data.Length == 6) { byte[] cipher = null; try { cipher = data[5] as byte[]; } catch { } if(cipher == null || cipher.Length == 0) { cookie.Value = data[0] as string; } else { win32api.DATA_BLOB input; input.pbData = Marshal.AllocHGlobal(cipher.Length); input.cbData = (uint)cipher.Length; Marshal.Copy(cipher, 0, input.pbData, cipher.Length); win32api.DATA_BLOB output = new win32api.DATA_BLOB(); win32api.DATA_BLOB dammy = new win32api.DATA_BLOB(); if(win32api.CryptUnprotectData(ref input, null, ref dammy, IntPtr.Zero, IntPtr.Zero, 0, ref output)) { Debug.WriteLine(base.Status.DisplayName + ": CryptUnprotectData ok"); byte[] plain = new byte[output.cbData]; Marshal.Copy(output.pbData, plain, 0, (int)output.cbData); cookie.Value = Encoding.UTF8.GetString(plain); if(win32api.LocalFree(output.pbData) == IntPtr.Zero) { Debug.WriteLine(base.Status.DisplayName + ": output.pbData free"); } } //Marshal.FreeHGlobal(input.pbData); if(win32api.LocalFree(input.pbData) == IntPtr.Zero) { Debug.WriteLine(base.Status.DisplayName + ": input.pbData free"); } } } else { cookie.Value = data[0] as string; } cookie.Name = data[1] as string; cookie.Domain = data[2] as string; cookie.Path = data[3] as string; if (cookie.Value != null) { cookie.Value = cookie.Value.Replace(";", "%3b").Replace(",", "%2c"); } try { long exp = long.Parse(data[4].ToString()); cookie.Expires = exp == 0 ? DateTime.MinValue : Utility.UnixTimeToDateTime((int)(exp / 1000000 - 11644473600)); } catch (Exception ex) { throw new CookieGetterException("GoogleChromeのexpires変換に失敗しました", ex); } return cookie; }
private void DownloadFile(ClipData clip, string folder) { string url = String.Format("http://{0}/DownloadFile.php?clip_id={1}", mediamanager.Server, clip.ID); System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); wr.CookieContainer = new System.Net.CookieContainer(); System.Net.Cookie cookie = new System.Net.Cookie("SESS1", mediamanager.ImpersonationToken, "/", mediamanager.Server); wr.CookieContainer.Add(cookie); System.IO.Stream stream = wr.GetResponse().GetResponseStream(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.Load(stream); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { HtmlAttribute att = link.Attributes["href"]; url = att.Value; break; } System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadProgressChanged += (s, e) => { if(e.ProgressPercentage > 0) { progressBar.Value = e.ProgressPercentage; } }; webClient.DownloadFileCompleted += (s, e) => { MessageBox.Show("Download complete"); }; webClient.DownloadFileAsync(new Uri(url), folder + @"\video.mp4"); }
private System.Net.Cookie getCookieRecode(System.IO.Stream stream, Header headerData) { Record recordData; System.Net.Cookie cookie = new System.Net.Cookie(); while (stream.Position < stream.Length) { recordData = getRecord(stream, headerData); switch (recordData.tag_id) { case 0x10: // Cookie Name cookie.Name = Encoding.ASCII.GetString(recordData.bytepayload); break; case 0x11: // Cookie Value cookie.Value = Encoding.ASCII.GetString(recordData.bytepayload); if (cookie.Value != null) { cookie.Value = Uri.EscapeDataString(cookie.Value); } break; case 0x12: long time; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(recordData.bytepayload)) { time = getNumber(ms, 8); } cookie.Expires = Utility.UnixTimeToDateTime((int)time); break; } } return cookie; }
private System.Net.Cookie GetFileToNicoCookie(Uri url, string key) { // いつも通りへぼいソース 2011-11-19 // へぼい内容→バイナリを無理矢理文字列にしてから正規表現でさくっと if(base.CookiePath == null || !File.Exists(base.CookiePath)) { return null; } System.Net.Cookie cookie = new System.Net.Cookie(); try { byte[] CookieData = System.IO.File.ReadAllBytes(base.CookiePath); String CookieTxt = Encoding.ASCII.GetString(CookieData); CookieTxt = CookieTxt.Replace("\0", "\t"); string regexText = string.Format("{0}_([0-9]+)_([0-9]+)", key); Match cookieChunk = Regex.Match(CookieTxt, @regexText, RegexOptions.Multiline); if(cookieChunk.Success) { try { cookie.Name = key; cookie.Value = string.Format("{0}_{1}_{2}", key, cookieChunk.Groups[1].Value, cookieChunk.Groups[2].Value); cookie.Domain = ".nicovideo.jp"; // 2011-11-19fix1 cookie.Path = "/"; } catch(Exception ex) { CookieGetter.Exceptions.Enqueue(ex); Debug.WriteLine(string.Format("Invalid Format! domain:{0},key:{1},value:{2}", cookie.Domain, cookie.Name, cookie.Value)); } } else { cookie = null; } } catch(Exception ex) { throw new CookieGetterException("Operaのクッキー取得中にエラーが発生しました。", ex); } return cookie; }
private static System.Net.CookieContainer FetLifeCookie() { string[] pairs = cookieString.Split(';'); var cookieContainer = new System.Net.CookieContainer(); Uri fl = new Uri("https://fetlife.com"); foreach (var item in pairs) { string[] splitItem = item.Split(new char[] { '=' }, 2); System.Net.Cookie cookie = new System.Net.Cookie(splitItem[0].Trim(), splitItem[1].Trim(), "/", fl.Host); cookieContainer.Add(cookie); } return cookieContainer; }
/// <summary> /// 指定されたファイルからクッキーを取得する /// </summary> /// <param name="filePath"></param> /// <returns></returns> protected virtual System.Net.Cookie[] PickCookiesFromFile(string filePath) { List<System.Net.Cookie> results = new List<System.Net.Cookie>(); try { string data = System.IO.File.ReadAllText(filePath, Encoding.GetEncoding("Shift_JIS")); string[] blocks = data.Split('*'); foreach(string block in blocks) { string[] lines = block.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if(7 < lines.Length) { System.Net.Cookie cookie = new System.Net.Cookie(); Uri uri = new Uri("http://" + lines[2]); cookie.Name = lines[0]; cookie.Value = lines[1]; cookie.Domain = uri.Host; cookie.Path = uri.AbsolutePath; // ドメインの最初に.をつける cookie.Domain = AddDotDomain(cookie.Domain); // 有効期限を取得する long uexp = 0, lexp = 0; if(long.TryParse(lines[4], out lexp) && long.TryParse(lines[5], out uexp)) { DateTime dt = FileTimeToDateTime(lexp, uexp); /* if(dt > DateTime.Now.AddMonths(2)) { dt = DateTime.Now; } */ cookie.Expires = dt; } if(cookie.Expires < DateTime.Now.AddMonths(12)) { results.Add(cookie); } } } } catch(Exception ex) { throw new CookieGetterException("IEクッキーの解析に失敗しました。", ex); } return results.ToArray(); }
// Функция чтобы получить куки для обычного HttpRequest или моего SimpleBrowser - проблема в том что на сайте посольства очень интересная проверка на подленость юзера public void GetCookiesFromDrive() { using (var Driver = new ChromeDriver()) { Globals.IdService = 1; Globals.IdCity = 92; Driver.Manage().Window.Maximize(); Driver.Navigate().GoToUrl("https://secure.e-konsulat.gov.pl/Uslugi/RejestracjaTerminu.aspx?IDUSLUGI=" + Globals.IdService + "&IDPlacowki=" + Globals.IdCity); if (Globals.IsElementDisplayed(Driver, By.Id("cp_KomponentObrazkowy_CaptchaImageID"))) { var cookies = Driver.Manage().Cookies.AllCookies; StreamWriter streamWriter = new StreamWriter(@"Cookies\" + Globals.cookieFileNameGuid + ".txt"); foreach (var result in cookies) { var cookieExpires = result.Expiry; var cookieDomain = result.Domain; var cookiePath = result.Path; var cookieName = result.Name; var cookieValue = result.Value; var cookieString = cookieName + ";" + cookieValue + ";" + cookiePath + ";" + cookieDomain + ";" + cookieExpires; streamWriter.WriteLine(cookieString); Console.WriteLine(cookieString); Cookie cookieNew = new Cookie(cookieName, cookieValue, cookiePath, cookieDomain); if (cookieExpires != null) cookieNew.Expires = (DateTime)cookieExpires; CapthaBrowser.Cookies.Add(cookieNew); } streamWriter.Close(); Driver.Close(); MessageBox.Show("Cookies has been saved!"); } else { MessageBox.Show("Error!"); Driver.Close(); } } }