Beispiel #1
0
        public HttpRequestWrapper(string url, HttpRequestMethod method, Encoding encode)
        {
            reqSetting = new HttpRequestSetting(url, method, encode);
            httpRequest = new HttpRequest();

            cookieParser = new CookieParser();
        }
Beispiel #2
0
 public static string GetCurrentCulture()
 {
     CookieParser parser = new CookieParser("Language");
     string languageStr = parser.GetValueToString();
     if (string.IsNullOrEmpty(languageStr)) languageStr = "zh";  //默认是中文
     return languageStr;
 }
Beispiel #3
0
        public void TestParser()
        {
            CookieCollection c;
            
            CookieParser parser = new CookieParser();
            CookieHeader header = (CookieHeader)parser.Parse("Cookie", new StringReader("name: \"Value\";cookie2: value2;cookieName;last:one"));
            Assert.Equal("Value", header.Cookies["name"].Value);
            Assert.Equal("value2", header.Cookies["cookie2"].Value);
            //Assert.Equal(string.Empty, header.Cookies["cookieName"].Value);
            Assert.Equal("one", header.Cookies["last"].Value);

        }
        public void WebSocketHandshaker_CanParseCookies()
        {
            CookieParser parser = new CookieParser();

            var parsed = parser.Parse("cookie1=uno").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(1, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);

            parsed = parser.Parse("cookie1=uno;cookie2=dos").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2=dos ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2===dos== ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("==dos==", parsed[1].Value);

            parsed = parser.Parse(null).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);

            parsed = parser.Parse(String.Empty).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);

            parsed = parser.Parse("   ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);
        }
Beispiel #5
0
        public void CoockieParser_Test()
        {
            //Arange
            const string coockieData = "1,TestRole";

            var parser = new CookieParser();

            var indentity = new FormsIdentity(
                new FormsAuthenticationTicket(
                    1,
                    "TestLogin",
                    new DateTime(1, 1, 1),
                    new DateTime(1, 1, 1),
                    false,
                    coockieData));

            var badIdentity = new FormsIdentity(
                new FormsAuthenticationTicket(
                    1,
                    "Test",
                    new DateTime(1, 1, 1),
                    new DateTime(1, 1, 1),
                    false,
                    "someBadCoockieData"));

            //Act
            var actualId       = parser.GetUserId(indentity);
            var actualRoleName = parser.GetUserRoleName(indentity);
            var actualLogin    = parser.GetUserLogin(indentity);

            //Assert
            Assert.Throws <ArgumentNullException>(() =>
                                                  parser.GetUserId(null));
            Assert.Throws <ArgumentNullException>(() =>
                                                  parser.GetUserRoleName(null));

            Assert.That(actualId == 1);
            Assert.That(actualRoleName == "TestRole");
            Assert.That(actualLogin == "TestLogin");

            Assert.Throws <CookieParserException>(() =>
                                                  parser.GetUserId(badIdentity));
            Assert.Throws <CookieParserException>(() =>
                                                  parser.GetUserRoleName(badIdentity));
        }
        public void CookieParser_NameAndValueOnly()
        {
            var cookieHeader = new List <string>()
            {
                "Name=Value"
            };

            var result = CookieParser.Parse(cookieHeader).Single();

            var expected = new HttpCookie("Name", "Value")
            {
                Path     = null,
                HttpOnly = false,
                Secure   = false
            };

            result.ShouldBeEquivalentTo(expected);
        }
        private async Task RevokeCookieTokens(IClient client, CookieParser cookieParser, CancellationToken cancellationToken)
        {
            var accessToken  = cookieParser.Get(_configuration.Web.AccessTokenCookie.Name);
            var refreshToken = cookieParser.Get(_configuration.Web.RefreshTokenCookie.Name);

            var revoker = new TokenRevoker(client, _logger)
                          .AddToken(accessToken)
                          .AddToken(refreshToken);

            try
            {
                await revoker.Revoke(cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.Info(ex.Message, source: nameof(RevokeCookieTokens));
            }
        }
        public void CookieParser_StrangeCasing()
        {
            var cookieHeader = new List <string>()
            {
                "Name=Value; dOmAin=example.com; ExPIres=Wed, 13 Jan 2021, 22:23:01 GMT; hTTPoNLy; SeCUre; PaTH=/SomePath"
            };

            var result = CookieParser.Parse(cookieHeader).Single();

            var expected = new HttpCookie("Name", "Value")
            {
                Domain   = "example.com",
                Expires  = new DateTime(2021, 01, 13, 22, 23, 01, DateTimeKind.Utc).ToLocalTime(),
                HttpOnly = true,
                Path     = "/SomePath",
                Secure   = true
            };

            result.ShouldBeEquivalentTo(expected);
        }
    private static void AddAuthenticationCookies(HttpContext context, System.Net.HttpWebRequest req)
    {
        // Copy user identity to new cookie
        if (context.User != null && context.User.Identity != null)
        {
            var cookiesString0 = req.Headers[HttpRequestHeader.Cookie];
            var cookies        = CookieParser.Parse(cookiesString0).ToList();

            // Pass username
            var userCookie = new Cookie("")
            {
                Name = "username", Value = context.User.Identity.Name
            };
            cookies.Add(userCookie);// Always add because this

            // Pass user groups
            var windowsIdentity = context.User.Identity as System.Security.Principal.WindowsIdentity;
            var groupNames      = new string[] { };
            if (windowsIdentity.Groups != null)
            {
                groupNames = windowsIdentity.Groups.Select(g => g.Translate(typeof(System.Security.Principal.NTAccount)).Value).ToArray();
            }
            var groupsCookie = new Cookie("")
            {
                Name = "usergroups", Value = string.Join(",", groupNames)
            };
            cookies.Add(groupsCookie);

            // Authentication ticket
            var ticket       = TicketHandler.IssueTicket();
            var ticketCookie = new Cookie("")
            {
                Name = "winauthticket", Value = ticket
            };
            cookies.Add(ticketCookie);

            var cookiesString = CookieParser.ToString(cookies.ToArray());
            req.Headers[HttpRequestHeader.Cookie] = cookiesString;
        }
    }
        public async Task HandleLogoutAsync(IOwinEnvironment context, CancellationToken cancellationToken)
        {
            var account = context.Request[OwinKeys.StormpathUser] as IAccount;

            var preLogoutContext = new PreLogoutContext(context, account);
            await _handlers.PreLogoutHandler(preLogoutContext, cancellationToken);

            // Remove user from request
            context.Request[OwinKeys.StormpathUser] = null;

            string[] rawCookies;
            context.Request.Headers.TryGetValue("Cookie", out rawCookies);
            var cookieParser = new CookieParser(rawCookies, _logger);

            await RevokeTokens(_client, cookieParser, cancellationToken);

            // TODO delete tokens for other types of auth too
            DeleteCookies(context, cookieParser);

            var postLogoutContext = new PostLogoutContext(context, account);
            await _handlers.PostLogoutHandler(postLogoutContext, cancellationToken);
        }
Beispiel #11
0
        internal static IEnumerable <string> GetCookiesFromHeader(string setCookieHeader)
        {
            List <string> cookieStrings = new List <string>();

            try
            {
                CookieParser parser = new CookieParser(setCookieHeader);
                string       cookieString;

                while ((cookieString = parser.GetString()) != null)
                {
                    cookieStrings.Add(cookieString);
                }
            }
            catch (InternalCookieException)
            {
                // TODO (#7856): We should log this.  But there isn't much we can do about it other
                // than to drop the rest of the cookies.
            }

            return(cookieStrings);
        }
Beispiel #12
0
        public void CookieParserGetServer_SetCookieHeaderValue_Success(string cookieString, string[] expectedStrings)
        {
            int index       = 0;
            int cookieCount = 0;
            var parser      = new CookieParser(cookieString);

            while (true)
            {
                Cookie cookie = parser.GetServer();
                if (cookie == null)
                {
                    break;
                }

                cookieCount++;
                Assert.Equal(expectedStrings[index++], cookie.Name);
                Assert.Equal(expectedStrings[index++], cookie.Value);
            }

            int expectedCookieCount = expectedStrings.Length >> 1;

            Assert.Equal(expectedCookieCount, cookieCount);
        }
Beispiel #13
0
        public HttpAuthHeaders BuildAuthHeaders()
        {
            var authCookieData          = "I can access this";
            var authCookieDataBytes     = Encoding.UTF8.GetBytes(authCookieData);
            var authCookieDataEncrypted = SymmetricEncryptor.Encrypt(encryptionAlgorithm, encryptionKey, authCookieDataBytes);
            var authCookieDataEncoded   = Base64UrlEncoder.ToBase64String(authCookieDataEncrypted);

            var cookies = new Dictionary <string, string>
            {
                { cookieName, authCookieDataEncoded }
            };

            var cookieHeaderValue = CookieParser.CookiesToString(cookies);
            var headers           = new HttpAuthHeaders
            {
                { cookieHeader, new List <string>()
                  {
                      cookieHeaderValue
                  } }
            };

            return(headers);
        }
Beispiel #14
0
        public void set_secure_is_case_insensitive()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; Secure;");

            cookie.Secure.ShouldBeTrue();
        }
Beispiel #15
0
        public void set_secure()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; secure;");

            cookie.Secure.ShouldBeTrue();
        }
Beispiel #16
0
        // This is used by the listener
        internal Replication ReplicationWithProperties(IDictionary <string, object> properties)
        {
            // Extract the parameters from the JSON request body:
            // http://wiki.apache.org/couchdb/Replication

            bool push, createTarget;
            var  results = new Dictionary <string, object>()
            {
                { "database", null },
                { "remote", null },
                { "headers", null },
                { "authorizer", null }
            };

            Status result = ParseReplicationProperties(properties, out push, out createTarget, results);

            if (result.IsError)
            {
                throw Misc.CreateExceptionAndLog(Log.To.Listener, result.Code, TAG, "Failed to create replication");
            }

            object continuousObj = properties.Get("continuous");
            bool   continuous    = false;

            if (continuousObj is bool)
            {
                continuous = (bool)continuousObj;
            }

            var         scheduler = new SingleTaskThreadpoolScheduler();
            Replication rep       = null;

            if (push)
            {
                rep = new Pusher((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }
            else
            {
                rep = new Puller((Database)results["database"], (Uri)results["remote"], continuous, new TaskFactory(scheduler));
            }

            rep.Filter       = properties.Get("filter") as string;
            rep.FilterParams = properties.Get("query_params").AsDictionary <string, object>();
            rep.DocIds       = properties.Get("doc_ids").AsList <string>();
            rep.Headers      = new Dictionary <string, string>();
            foreach (var header in results.Get("headers").AsDictionary <string, string>())
            {
                if (header.Key.ToLowerInvariant() == "cookie")
                {
                    var cookie = default(Cookie);
                    if (CookieParser.TryParse(header.Value, ((Uri)results["remote"]).GetLeftPart(UriPartial.Authority), out cookie))
                    {
                        rep.SetCookie(cookie.Name, cookie.Value, cookie.Path, cookie.Expires, cookie.Secure, cookie.HttpOnly);
                    }
                    else
                    {
                        Log.To.Listener.W(TAG, "Invalid cookie string received ({0}), ignoring...", header.Value);
                    }
                }
                else
                {
                    rep.Headers.Add(header.Key, header.Value);
                }
            }
            rep.Headers       = results.Get("headers").AsDictionary <string, string>();
            rep.Authenticator = results.Get("authorizer") as IAuthenticator;
            if (push)
            {
                ((Pusher)rep).CreateTarget = createTarget;
            }

            var db = (Database)results["database"];

            // If this is a duplicate, reuse an existing replicator:
            var activeReplicators = default(IList <Replication>);
            var existing          = default(Replication);

            if (db.ActiveReplicators.AcquireTemp(out activeReplicators))
            {
                existing = activeReplicators.FirstOrDefault(x => x.LocalDatabase == rep.LocalDatabase &&
                                                            x.RemoteUrl == rep.RemoteUrl && x.IsPull == rep.IsPull &&
                                                            x.RemoteCheckpointDocID().Equals(rep.RemoteCheckpointDocID()));
            }


            return(existing ?? rep);
        }
Beispiel #17
0
        // copy-pasted (and a bit adapted) from HttpWebResponse
        void SetCookie(string header)
        {
            string       name, val;
            Cookie       cookie = null;
            CookieParser parser = new CookieParser(header);

            while (parser.GetNextNameValue(out name, out val))
            {
                if (String.IsNullOrEmpty(name) && cookie == null)
                {
                    continue;
                }

                if (cookie == null)
                {
                    cookie = new Cookie(name, val);
                    continue;
                }

                name = name.ToUpper();
                switch (name)
                {
                case "COMMENT":
                    if (cookie.Comment == null)
                    {
                        cookie.Comment = val;
                    }
                    break;

                case "COMMENTURL":
                    if (cookie.CommentUri == null)
                    {
                        cookie.CommentUri = new Uri(val);
                    }
                    break;

                case "DISCARD":
                    cookie.Discard = true;
                    break;

                case "DOMAIN":
                    if (cookie.Domain.Length == 0)
                    {
                        cookie.Domain = val;
                    }
                    break;

                case "HTTPONLY":
                    cookie.HttpOnly = true;
                    break;

                case "MAX-AGE":                 // RFC Style Set-Cookie2
                    if (cookie.Expires == DateTime.MinValue)
                    {
                        try {
                            cookie.Expires = cookie.TimeStamp.AddSeconds(UInt32.Parse(val));
                        } catch {}
                    }
                    break;

                case "EXPIRES":                 // Netscape Style Set-Cookie
                    if (cookie.Expires != DateTime.MinValue)
                    {
                        break;
                    }

                    cookie.Expires = CookieParser.TryParseCookieExpires(val);
                    break;

                case "PATH":
                    cookie.Path = val;
                    break;

                case "PORT":
                    if (cookie.Port == null)
                    {
                        cookie.Port = val;
                    }
                    break;

                case "SECURE":
                    cookie.Secure = true;
                    break;

                case "VERSION":
                    try {
                        cookie.Version = (int)UInt32.Parse(val);
                    } catch {}
                    break;
                }
            }

            if (cookie.Domain.Length == 0)
            {
                cookie.Domain = response_uri.Host;
            }

            jar.Add(cookie);
        }
Beispiel #18
0
        public void sets_the_domain_is_case_insensitive()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com");

            cookie.Domain.ShouldEqual("http://cnn.com");
        }
Beispiel #19
0
        public void expires_is_not_set_by_default()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com;");

            cookie.Expires.ShouldBeNull();
        }
Beispiel #20
0
        public void set_http_only_is_case_insensitive()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; HttpOnly;");

            cookie.HttpOnly.ShouldBeTrue();
        }
Beispiel #21
0
        public void WebSocketHandshaker_CanParseCookies()
        {
            CookieParser parser = new CookieParser();

            var parsed = parser.Parse("cookie1=uno").ToArray();

            Assert.IsNotNull(parsed);
            Assert.AreEqual(1, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);

            parsed = parser.Parse("cookie1=uno;cookie2=dos").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2=dos ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2===dos== ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("==dos==", parsed[1].Value);

            parsed = parser.Parse("language=ru; _ym_uid=1111111111111; _ym_isad=2; __test; settings=%7B%22market_730_onPage%22%3A24%7D; timezoneOffset=10800").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(6, parsed.Length);
            Assert.AreEqual("language", parsed[0].Name);
            Assert.AreEqual("ru", parsed[0].Value);
            Assert.AreEqual("_ym_uid", parsed[1].Name);
            Assert.AreEqual("1111111111111", parsed[1].Value);
            Assert.AreEqual("_ym_isad", parsed[2].Name);
            Assert.AreEqual("2", parsed[2].Value);
            Assert.AreEqual("__test", parsed[3].Name);
            Assert.AreEqual("", parsed[3].Value);
            Assert.AreEqual("settings", parsed[4].Name);
            Assert.AreEqual("{\"market_730_onPage\":24}", parsed[4].Value);
            Assert.AreEqual("timezoneOffset", parsed[5].Name);
            Assert.AreEqual("10800", parsed[5].Value);

            parsed = parser.Parse(null).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);

            parsed = parser.Parse(String.Empty).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);

            parsed = parser.Parse("   ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);
        }
Beispiel #22
0
 private static string GetLanguageFromClient()
 {
     CookieParser parser = new CookieParser("Language");
     string languageStr = parser.GetValueToString();
     if (!string.IsNullOrEmpty(languageStr) && IsSupportLanguage(languageStr))
         return languageStr;
     return string.Empty;
 }
Beispiel #23
0
        public void set_the_path()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; path=foo;");

            cookie.Path.ShouldEqual("foo");
        }
Beispiel #24
0
        private void roundTrip(string text)
        {
            var cookie = CookieParser.ToCookie(text);

            cookie.ToString().ShouldEqual(text);
        }
Beispiel #25
0
 public void split_values()
 {
     CookieParser.SplitValues("a=b;c=d;").ShouldHaveTheSameElementsAs("a=b", "c=d");
 }
 private void ParseCookies(WebSocketHandshake handshake)
 {
     if (handshake.Request.Headers.HeaderNames.Contains("Cookie"))
     {
         var cookieString = handshake.Request.Headers["Cookie"];
         try
         {
             CookieParser parser = new CookieParser();
             foreach (var cookie in parser.Parse(cookieString))
             {
                 cookie.Domain = handshake.Request.Headers.Host;
                 cookie.Path = String.Empty;
                 handshake.Request.Cookies.Add(cookie);
             }
         }
         catch (Exception ex)
         {
             throw new WebSocketException("Cannot parse cookie string: '" + (cookieString ?? "") + "' because: " + ex.Message);
         }
     }
 }
Beispiel #27
0
        public void do_not_set_secure()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com;");

            cookie.Secure.ShouldBeFalse();
        }
        public void WebSocketHandshaker_CanParseCookies()
        {
            CookieParser parser = new CookieParser();

            var parsed = parser.Parse("cookie1=uno").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(1, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);

            parsed = parser.Parse("cookie1=uno;cookie2=dos").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2=dos ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("dos", parsed[1].Value);

            parsed = parser.Parse("cookie1=uno; cookie2===dos== ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(2, parsed.Length);
            Assert.AreEqual("cookie1", parsed[0].Name);
            Assert.AreEqual("uno", parsed[0].Value);
            Assert.AreEqual("cookie2", parsed[1].Name);
            Assert.AreEqual("==dos==", parsed[1].Value);

            parsed = parser.Parse("language=ru; _ym_uid=1111111111111; _ym_isad=2; __test; settings=%7B%22market_730_onPage%22%3A24%7D; timezoneOffset=10800").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(6, parsed.Length);
            Assert.AreEqual("language", parsed[0].Name);
            Assert.AreEqual("ru", parsed[0].Value);
            Assert.AreEqual("_ym_uid", parsed[1].Name);
            Assert.AreEqual("1111111111111", parsed[1].Value);
            Assert.AreEqual("_ym_isad", parsed[2].Name);
            Assert.AreEqual("2", parsed[2].Value);
            Assert.AreEqual("__test", parsed[3].Name);
            Assert.AreEqual("", parsed[3].Value);
            Assert.AreEqual("settings", parsed[4].Name);
            Assert.AreEqual("{\"market_730_onPage\":24}", parsed[4].Value);
            Assert.AreEqual("timezoneOffset", parsed[5].Name);
            Assert.AreEqual("10800", parsed[5].Value);

            parsed = parser.Parse(null).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);
            
            parsed = parser.Parse(String.Empty).ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);

            parsed = parser.Parse("   ").ToArray();
            Assert.IsNotNull(parsed);
            Assert.AreEqual(0, parsed.Length);
        }
Beispiel #29
0
        public void set_http_only()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; httponly;");

            cookie.HttpOnly.ShouldBeTrue();
        }
 private void DeleteCookies(IOwinEnvironment context, CookieParser cookieParser)
 {
     Cookies.DeleteTokenCookie(context, _configuration.Web.AccessTokenCookie, _logger);
     Cookies.DeleteTokenCookie(context, _configuration.Web.RefreshTokenCookie, _logger);
 }
Beispiel #31
0
        public void http_only_is_not_set_by_default()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com;");

            cookie.HttpOnly.ShouldBeFalse();
        }
Beispiel #32
0
		// copy-pasted (and a bit adapted) from HttpWebResponse
		void SetCookie (string header)
		{
			string name, val;
			Cookie cookie = null;
			CookieParser parser = new CookieParser (header);

			while (parser.GetNextNameValue (out name, out val)) {
				if (String.IsNullOrEmpty (name) && cookie == null)
					continue;

				if (cookie == null) {
					cookie = new Cookie (name, val);
					continue;
				}

				name = name.ToUpper ();
				switch (name) {
				case "COMMENT":
					if (cookie.Comment == null)
						cookie.Comment = val;
					break;
				case "COMMENTURL":
					if (cookie.CommentUri == null)
						cookie.CommentUri = new Uri (val);
					break;
				case "DISCARD":
					cookie.Discard = true;
					break;
				case "DOMAIN":
					if (cookie.Domain.Length == 0)
						cookie.Domain = val;
					break;
				case "HTTPONLY":
					cookie.HttpOnly = true;
					break;
				case "MAX-AGE": // RFC Style Set-Cookie2
					if (cookie.Expires == DateTime.MinValue) {
						try {
						cookie.Expires = cookie.TimeStamp.AddSeconds (UInt32.Parse (val));
						} catch {}
					}
					break;
				case "EXPIRES": // Netscape Style Set-Cookie
					if (cookie.Expires != DateTime.MinValue)
						break;

					cookie.Expires = CookieParser.TryParseCookieExpires (val);
					break;
				case "PATH":
					cookie.Path = val;
					break;
				case "PORT":
					if (cookie.Port == null)
						cookie.Port = val;
					break;
				case "SECURE":
					cookie.Secure = true;
					break;
				case "VERSION":
					try {
						cookie.Version = (int) UInt32.Parse (val);
					} catch {}
					break;
				}
			}

			if (cookie.Domain.Length == 0)
				cookie.Domain = response_uri.Host;

			jar.Add (cookie);
		}
Beispiel #33
0
        public void sets_the_domain()
        {
            var cookie = CookieParser.ToCookie("a=1; domain=http://cnn.com");

            cookie.Domain.ShouldEqual("http://cnn.com");
        }
Beispiel #34
0
        private static int Main(string[] args)
        {
            Error error = 0;

            var output          = ".";
            var profile         = "profile.toml";
            var template        = "template.html";
            var showHelpAndExit = false;

            var options = new OptionSet
            {
                { "o|output=", $"Reports output directory\n(default: '{output}')", v => output = v },
                { "p|profile=", $"Profile TOML file with current settings\n(default: '{profile}')", v => profile = v },
                { "t|template=", $"HTML report template file\n(default: '{template}')", v => template = v },
                { "h|help", "Show this message", v => showHelpAndExit = v != null }
            };

            List <string> free = null;

            try
            {
                free = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Error.WriteLine("Option '{0}' value is invalid: {1}", e.OptionName, e.Message);
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            if (!PathHelper.FileExistsWithOptionalExt(ref profile, ".toml"))
            {
                Console.Error.WriteLine($"Profile '{profile}' not found");
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            if (!PathHelper.FileExistsWithOptionalExt(ref template, ".html"))
            {
                Console.Error.WriteLine($"Template '{template}' not found");
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            Settings settings = null;

            try
            {
                settings = Settings.Read(profile.RelativeToBaseDirectory());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"Failed to read profile '{profile}': {e.Message}");
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            try
            {
                if (free?.Count >= 2)
                {
                    SvcLeft  = new Uri(free[0]);
                    SvcRight = new Uri(free[1]);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            var input = free?.Skip(2).FirstOrDefault();

            if (input != null && !File.Exists(input.RelativeToBaseDirectory()))
            {
                Console.Error.WriteLine("Input file with URLs not found");
                Console.Error.WriteLine();
                error = Error.InvalidArgs;
            }

            if (showHelpAndExit || error != 0 || settings == null || free == null || free.Count < 2)
            {
                Console.WriteLine("Usage: webdiff [OPTIONS] URL1 URL2 [FILE]");
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                Console.WriteLine();
                Console.WriteLine("Examples:");
                Console.WriteLine("  webdiff http://prod.example.com http://test.example.com < URLs.txt");
                Console.WriteLine("  webdiff -p profile.toml -t template.html -o data http://prod.example.com http://test.example.com URLs.txt");
                Console.WriteLine();
                return((int)error);
            }

            Cookie[] cookies = null;
            try
            {
                if (settings.Driver.Cookies != null)
                {
                    cookies = CookieParser.Parse(settings.Driver.Cookies.RelativeToBaseDirectory());
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"Failed to parse cookies file: {e.Message}");
                return((int)Error.InvalidArgs);
            }

            var started = DateTime.Now;

            try
            {
                ResultsPath    = Path.Combine(output, started.ToString("yyyyMMdd-HHmmss")).RelativeToBaseDirectory();
                ResultsImgPath = Path.Combine(ResultsPath, ImgRelativePath);

                Directory.CreateDirectory(ResultsPath);
                Directory.CreateDirectory(ResultsImgPath);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine($"Failed to create output directory '{ResultsPath}': {e.Message}");
                return((int)Error.CestLaVie);
            }

            (Uri BaseUri, RemoteWebDriver Driver)[] drivers = null;
Beispiel #35
0
        public void set_The_max_age()
        {
            var cookie = CookieParser.ToCookie("a=1; domain=http://cnn.com; max-age=5");

            cookie.MaxAge.ShouldEqual(5.Seconds());
        }
        private async Task <IAccount> TryCookieAuthenticationAsync(IOwinEnvironment context, IClient client)
        {
            string[] rawCookies = null;

            if (!context.Request.Headers.TryGetValue("Cookie", out rawCookies))
            {
                logger.Trace("No cookie header found", nameof(TryCookieAuthenticationAsync));
                return(null);
            }

            var cookieParser = new CookieParser(rawCookies, logger);

            if (cookieParser.Count == 0)
            {
                logger.Trace("No cookies parsed from header", nameof(TryCookieAuthenticationAsync));
                return(null);
            }

            logger.Trace("Cookies found on request: " + cookieParser.AsEnumerable().Select(x => $"'{x.Key}'").Join(", "), nameof(TryCookieAuthenticationAsync));

            var accessToken  = cookieParser.Get(this.Configuration.Web.AccessTokenCookie.Name);
            var refreshToken = cookieParser.Get(this.Configuration.Web.RefreshTokenCookie.Name);

            // Attempt to validate incoming Access Token
            if (!string.IsNullOrEmpty(accessToken))
            {
                logger.Trace($"Found nonempty access token cookie '{this.Configuration.Web.AccessTokenCookie.Name}'", nameof(TryCookieAuthenticationAsync));

                var validAccount = await ValidateAccessTokenAsync(context, client, accessToken);

                if (validAccount != null)
                {
                    logger.Info("Request authenticated using Access Token cookie", nameof(TryCookieAuthenticationAsync));
                    return(validAccount);
                }
                else
                {
                    logger.Info("Access token cookie was not valid", nameof(TryCookieAuthenticationAsync));
                }
            }

            // Try using refresh token instead
            if (!string.IsNullOrEmpty(refreshToken))
            {
                logger.Trace($"Found nonempty refresh token cookie '{this.Configuration.Web.RefreshTokenCookie.Name}'", nameof(TryCookieAuthenticationAsync));

                var refreshedAccount = await RefreshAccessTokenAsync(context, client, refreshToken);

                if (refreshedAccount != null)
                {
                    logger.Info("Request authenticated using Refresh Token cookie", nameof(TryCookieAuthenticationAsync));
                    return(refreshedAccount);
                }
                else
                {
                    logger.Info("Refresh token cookie was not valid", nameof(TryCookieAuthenticationAsync));
                }
            }

            // Failed on both counts. Delete access and refresh token cookies if necessary
            if (cookieParser.Contains(this.Configuration.Web.AccessTokenCookie.Name))
            {
                Cookies.DeleteTokenCookie(context, this.Configuration.Web.AccessTokenCookie, logger);
            }
            if (cookieParser.Contains(this.Configuration.Web.RefreshTokenCookie.Name))
            {
                Cookies.DeleteTokenCookie(context, this.Configuration.Web.RefreshTokenCookie, logger);
            }

            logger.Info("No access or refresh token cookies found", nameof(TryCookieAuthenticationAsync));
            return(null);
        }
Beispiel #37
0
        public void set_The_path_with_default_value_2()
        {
            var cookie = CookieParser.ToCookie("a=1; Domain=http://cnn.com; path;");

            cookie.Path.ShouldEqual("/");
        }
Beispiel #38
0
 public void ExpirationParse() =>
 CookieParser.FromString("username=op; Expires=Wed, 03 Jan 2018 14:54:50 GMT")
 .Assert(cookie =>
         cookie.Name == "username" &&
         cookie.Value == "op" &&
         cookie.Expires == new DateTime(2018, 01, 3, 14, 54, 50, DateTimeKind.Utc));