Exemplo n.º 1
0
        static Cookie ToNetCookie(NSHttpCookie cookie)
        {
            var nc = new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);

            nc.Secure = cookie.IsSecure;
            return(nc);
        }
Exemplo n.º 2
0
        public void DotNetInteropMax()
        {
            var c = new Cookie("name", "key", "path", "domain");

            c.Comment    = "comment";
            c.CommentUri = new Uri("http://comment.uri");
            c.Discard    = true;
            c.Expires    = DateTime.Now.AddDays(1);
            c.HttpOnly   = false;
            c.Port       = "\"80\"";
            c.Secure     = true;
            c.Version    = 1;
            using (NSHttpCookie cookie = new NSHttpCookie(c)) {
                Assert.That(cookie.Name, Is.EqualTo("name"), "Name");
                Assert.That(cookie.Value, Is.EqualTo("key"), "Value");
                Assert.That(cookie.Path, Is.EqualTo("path"), "Path");
                Assert.That(cookie.Domain, Is.EqualTo("domain"), "Domain");
                // custom values
                Assert.That(cookie.Comment, Is.EqualTo("comment"), "Comment");
                Assert.That(cookie.CommentUrl.ToString(), Is.EqualTo("http://comment.uri/"), "CommentUrl");
                Assert.Null(cookie.ExpiresDate, "ExpiresDate");                  // session-only always returns null
                Assert.False(cookie.IsHttpOnly, "IsHttpOnly");
                Assert.True(cookie.IsSecure, "IsSecure");
                Assert.True(cookie.IsSessionOnly, "IsSessionOnly");
                Assert.That((int)cookie.PortList [0], Is.EqualTo(80), "PortList");
                Assert.NotNull(cookie.Properties, "Properties");
                Assert.That(cookie.Version, Is.EqualTo((nuint)1), "Version");
            }
        }
        /// <summary>
        /// Converts to CLR cookie.
        /// </summary>
        /// <returns>The to CLR cookie.</returns>
        /// <param name="self">Self.</param>
        public static Cookie ConvertToCLRCookie(this NSHttpCookie self)
        {
            if (self == null)
            {
                return(null);
            }
#if DEBUG
            Console.WriteLine("Name: {0}", self.Name);
            Console.WriteLine("Value: {0}", self.Value);
            Console.WriteLine("Version: {0}", self.Version);
            Console.WriteLine("ExpiresDate: {0}", self.ExpiresDate);
            Console.WriteLine("Domain: {0}", self.Domain);
            Console.WriteLine("Path: {0}", self.Path);
            Console.WriteLine("IsSecure: {0}", self.IsSecure);
            Console.WriteLine("IsHttpOnly: {0}", self.IsHttpOnly);
#endif
            System.Net.Cookie newCookie = new System.Net.Cookie()
            {
                Name    = self.Name,
                Value   = self.Value,
                Version = (int)self.Version,
                Expires = (self.ExpiresDate != null) ? (DateTime)self.ExpiresDate : DateTime.MaxValue,
                Domain  = self.Domain,
                Path    = self.Path,
//				Port = (self.PortList.Length > 0) ? self.PortList[0].ToString() : null,
                Secure   = self.IsSecure,
                HttpOnly = self.IsHttpOnly
            };


            return(newCookie);
        }
        static Cookie ToNetCookie(NSHttpCookie cookie)
        {
            var nc = new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);
            nc.Secure = cookie.IsSecure;

            return nc;
        }
Exemplo n.º 5
0
        public void CookieFromProperties()
        {
            using (var props = new NSMutableDictionary()) {
#if XAMCORE_2_0
                props.Add(NSHttpCookie.KeyOriginUrl, new NSString("http://yodawg.com"));
#else
                props.Add(NSHttpCookie.KeyOriginURL, new NSString("http://yodawg.com"));
#endif
                props.Add(NSHttpCookie.KeyName, new NSString("iherd"));
                props.Add(NSHttpCookie.KeyValue, new NSString("ulikecookies"));

                var cookie = NSHttpCookie.CookieFromProperties(props);
                Assert.Null(cookie, "missing path");

                props.Add(NSHttpCookie.KeyPath, new NSString("/"));
                using (cookie = NSHttpCookie.CookieFromProperties(props)) {
                    Assert.NotNull(cookie, "w/path");

                    Assert.That(cookie.Domain, Is.EqualTo("yodawg.com"), "Domain");
                    Assert.That(cookie.Name, Is.EqualTo("iherd"), "Name");
                    Assert.That(cookie.Value, Is.EqualTo("ulikecookies"), "Value");
                    Assert.That(cookie.Path, Is.EqualTo("/"), "Path");
                }
            }
        }
        private async Task <string> OnSetCookieRequestAsync(Cookie cookie)
        {
            if (Control == null)
            {
                return(string.Empty);
            }
            var toReturn = string.Empty;

            try
            {
                var domain    = Control.Url.Host;
                var newCookie = new NSHttpCookie(cookie);

                NSHttpCookieStorage.SharedStorage.SetCookie(newCookie);

                var store = _configuration.WebsiteDataStore.HttpCookieStore;
                store.SetCookie(newCookie, () => { });

                toReturn = await OnGetCookieRequestAsync(cookie.Name);
            }
            catch (Exception e)
            {
                Console.WriteLine("We had a crash " + e);
                toReturn = string.Empty;
            }
            return(toReturn);
        }
Exemplo n.º 7
0
        public void DotNetInterop_NonSession()
        {
            var c = new Cookie("name", "key", "path", "domain");

            c.Comment    = "comment";
            c.CommentUri = new Uri("http://comment.uri");
            c.Discard    = false;
            c.Expires    = DateTime.Now.AddDays(1);
            c.HttpOnly   = false;
            c.Port       = "\"80\"";
            c.Secure     = true;
            c.Version    = 1;
            using (NSHttpCookie cookie = new NSHttpCookie(c)) {
                Assert.That(cookie.Name, Is.EqualTo("name"), "Name");
                Assert.That(cookie.Value, Is.EqualTo("key"), "Value");
                Assert.That(cookie.Path, Is.EqualTo("path"), "Path");
                Assert.That(cookie.Domain, Is.EqualTo("domain"), "Domain");
                // custom values
                Assert.That(cookie.Comment, Is.EqualTo("comment"), "Comment");
                Assert.That(cookie.CommentUrl.ToString(), Is.EqualTo("http://comment.uri/"), "CommentUrl");
                DateTime dt1 = (DateTime)cookie.ExpiresDate;                  // does not include milliseconds (so we do a string match)
                DateTime dt2 = c.Expires.ToUniversalTime();
                Assert.That(dt1.ToString(), Is.EqualTo(dt2.ToString()), "ExpiresDate");
                Assert.False(cookie.IsHttpOnly, "IsHttpOnly");
                Assert.True(cookie.IsSecure, "IsSecure");
                Assert.IsFalse(cookie.IsSessionOnly, "IsSessionOnly");
                Assert.That((int)cookie.PortList [0], Is.EqualTo(80), "PortList");
                Assert.NotNull(cookie.Properties, "Properties");
                Assert.That(cookie.Version, Is.EqualTo((nuint)1), "Version");
            }
        }
Exemplo n.º 8
0
        public void NSDictionaryCtor()
        {
            using (var props = new NSMutableDictionary()) {
#if XAMCORE_2_0
                props.Add(NSHttpCookie.KeyOriginUrl, new NSString("http://yodawg.com"));
#else
                props.Add(NSHttpCookie.KeyOriginURL, new NSString("http://yodawg.com"));
#endif
                props.Add(NSHttpCookie.KeyName, new NSString("iherd"));
                props.Add(NSHttpCookie.KeyValue, new NSString("ulikecookies"));

                // an invalid NSDictionary returns null from Objective-C but that
                // results in an 'empty' instance inside MonoTouch
                Assert.Throws <Exception> (() => new NSHttpCookie(props), "ctor");

                props.Add(NSHttpCookie.KeyPath, new NSString("/"));
                using (var cookie = new NSHttpCookie(props)) {
                    Assert.That(cookie.Handle, Is.Not.EqualTo(IntPtr.Zero), "ctor");

                    Assert.That(cookie.Domain, Is.EqualTo("yodawg.com"), "Domain");
                    Assert.That(cookie.Name, Is.EqualTo("iherd"), "Name");
                    Assert.That(cookie.Value, Is.EqualTo("ulikecookies"), "Value");
                    Assert.That(cookie.Path, Is.EqualTo("/"), "Path");
                }
            }
        }
        private async Task OnAddCookieRequested(System.Net.Cookie cookie)
        {
            if (Control == null || cookie == null || String.IsNullOrEmpty(cookie.Domain) || String.IsNullOrEmpty(cookie.Name))
            {
                return;
            }

            var nsCookie = new NSHttpCookie(cookie);

            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                var store = _configuration.WebsiteDataStore.HttpCookieStore;
                await store.SetCookieAsync(nsCookie);
            }
            NSHttpCookieStorage.SharedStorage.SetCookie(nsCookie);
            foreach (var cookies in NSHttpCookieStorage.SharedStorage.Cookies)
            {
                System.Diagnostics.Debug.WriteLine(cookie.ToString());
            }

            if (!_cookieDomains.ContainsKey(cookie.Domain))
            {
                _cookieDomains[cookie.Domain] = 0;
            }
            _cookieDomains[cookie.Domain] = _cookieDomains[cookie.Domain] + 1;
#if DEBUG
            await OnPrintCookiesRequested();
#endif
        }
        protected void SetCookies(Uri uri, string v)
        {
            CachedCookieStore.Clear();
#if __DROID__
            var prefs = Android.App.Application.Context.GetSharedPreferences("Cookies", Android.Content.FileCreationMode.Private);
            prefs.Edit().PutString(uri.ToString(), v).Commit();

            //CookieManager.Instance.SetCookie(uri.ToString(), v);
            //try
            //{
            //    CookieManager.Instance.Flush();
            //}
            //catch {
            //}
#endif
#if __IOS__
            var cookieParser = new CookieContainer();
            cookieParser.SetCookies(uri, v);

            foreach (System.Net.Cookie cookie in cookieParser.GetCookies(uri))
            {
                NSHttpCookie nsc = new NSHttpCookie(cookie);
                NSHttpCookieStorage.SharedStorage.SetCookie(nsc);
            }
#endif
        }
Exemplo n.º 11
0
        public static Cookie ToCookie(this NSHttpCookie nscookie, bool setDomain = true)
        {
            Uri commentUri = null;

            if (nscookie.CommentUrl != null)
            {
                commentUri = nscookie.CommentUrl;
            }

            Cookie cookie = new Cookie()
            {
                Comment    = nscookie.Comment,
                CommentUri = commentUri,
                Expires    = nscookie.ExpiresDate.ToDateTime(),
                HttpOnly   = nscookie.IsHttpOnly,
                Name       = nscookie.Name,
                Path       = nscookie.Path,
                Secure     = nscookie.IsSecure,
                Value      = nscookie.Value,
                Version    = (int)nscookie.Version,
                Port       = String.Join(",", nscookie.PortList.Select(x => x.ToString()))
            };

            if (setDomain)
            {
                cookie.Domain = nscookie.Domain;
            }

            return(cookie);
        }
Exemplo n.º 12
0
        public void SetCookie(Cookie cookie)
        {
            NSHttpCookie httpCookie = new NSHttpCookie(cookie);

            NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
            NSHttpCookieStorage.SharedStorage.SetCookie(httpCookie);
        }
Exemplo n.º 13
0
        public void DotNetInterop_NonSession()
        {
            var c = new Cookie("name", "key", "path", "domain");

            c.Comment    = "comment";
            c.CommentUri = new Uri("http://comment.uri");
            c.Discard    = false;
            c.Expires    = DateTime.Now.AddDays(1);
            c.HttpOnly   = false;
            c.Port       = "\"80\"";
            c.Secure     = true;
            c.Version    = 1;
            using (NSHttpCookie cookie = new NSHttpCookie(c)) {
                Assert.That(cookie.Name, Is.EqualTo("name"), "Name");
                Assert.That(cookie.Value, Is.EqualTo("key"), "Value");
                Assert.That(cookie.Path, Is.EqualTo("path"), "Path");
                Assert.That(cookie.Domain, Is.EqualTo("domain"), "Domain");
                // custom values
                Assert.That(cookie.Comment, Is.EqualTo("comment"), "Comment");
                Assert.That(cookie.CommentUrl.ToString(), Is.EqualTo("http://comment.uri/"), "CommentUrl");
                DateTime dt1 = (DateTime)cookie.ExpiresDate;                  // does not include milliseconds (so we do a string match)
                DateTime dt2 = c.Expires.ToUniversalTime();
                // There seems to be rounding somewhere, which means that some dates
                // can be rounded up. This means that these two dates might be a second off.
                // So assert that they're no more than a second apart.
                Assert.That(Math.Abs((dt1 - dt2).TotalSeconds), Is.LessThan(1.0), $"ExpiresDate");
                Assert.False(cookie.IsHttpOnly, "IsHttpOnly");
                Assert.True(cookie.IsSecure, "IsSecure");
                Assert.IsFalse(cookie.IsSessionOnly, "IsSessionOnly");
                Assert.That((int)cookie.PortList [0], Is.EqualTo(80), "PortList");
                Assert.NotNull(cookie.Properties, "Properties");
                Assert.That(cookie.Version, Is.EqualTo((nuint)1), "Version");
            }
        }
Exemplo n.º 14
0
        public void PortList_4990()
        {
            Cookie c = new Cookie();

            c.Comment    = String.Empty;
            c.CommentUri = null;
            c.Discard    = true;
            c.Domain     = ".collectedit.com";
            c.Expired    = false;
            c.Expires    = DateTime.Now.AddMonths(1);
            c.HttpOnly   = true;
            c.Name       = ".ASPXAUTH";
            c.Path       = "/";
            c.Port       = String.Empty;
            c.Secure     = false;
            c.Value      = "abc";
            using (NSHttpCookie c1 = new NSHttpCookie(c))
                using (NSHttpCookie c2 = new NSHttpCookie(".ASPXAUTH", "abc", "/", ".collectedit.com")) {
                    Assert.That(c1.Name, Is.EqualTo(c2.Name), "Name");
                    Assert.That(c1.Value, Is.EqualTo(c2.Value), "Value");
                    Assert.That(c1.Path, Is.EqualTo(c2.Path), "Path");
                    Assert.That(c1.Domain, Is.EqualTo(c2.Domain), "Domain");
                    Assert.That(c1.Comment, Is.EqualTo(c2.Comment), "Comment");
                    Assert.That(c1.CommentUrl, Is.EqualTo(c2.CommentUrl), "CommentUrl");
                    Assert.That(c1.ExpiresDate, Is.EqualTo(c2.ExpiresDate), "ExpiresDate");
                    Assert.That(c1.IsHttpOnly, Is.EqualTo(c2.IsHttpOnly), "IsHttpOnly");
                    Assert.That(c1.IsSecure, Is.EqualTo(c2.IsSecure), "IsSecure");
                    Assert.That(c1.IsSessionOnly, Is.EqualTo(c2.IsSessionOnly), "IsSessionOnly");
                    Assert.That(c1.PortList, Is.EqualTo(c2.PortList), "PortList");
                    Assert.That(c1.Version, Is.EqualTo(c2.Version), "Version");
                }
        }
Exemplo n.º 15
0
        internal async Task SyncNativeCookiesToElement(string url)
        {
            if (String.IsNullOrWhiteSpace(url))
            {
                return;
            }

            var myCookieJar = WebView.Cookies;

            if (myCookieJar == null)
            {
                return;
            }

            var uri = CreateUriForCookies(url);

            if (uri == null)
            {
                return;
            }

            var cookies = myCookieJar.GetCookies(uri);
            var retrieveCurrentWebCookies = await GetCookiesFromNativeStore(url);

            foreach (var nscookie in retrieveCurrentWebCookies)
            {
                if (cookies[nscookie.Name] == null)
                {
                    string cookieH = $"{nscookie.Name}={nscookie.Value}; domain={nscookie.Domain}; path={nscookie.Path}";

                    myCookieJar.SetCookies(uri, cookieH);
                }
            }

            foreach (Cookie cookie in cookies)
            {
                NSHttpCookie nSHttpCookie = null;

                foreach (var findCookie in retrieveCurrentWebCookies)
                {
                    if (findCookie.Name == cookie.Name)
                    {
                        nSHttpCookie = findCookie;
                        break;
                    }
                }

                if (nSHttpCookie == null)
                {
                    cookie.Expired = true;
                }
                else
                {
                    cookie.Value = nSHttpCookie.Value;
                }
            }

            await SyncNativeCookies(url);
        }
Exemplo n.º 16
0
 public void GetNSObject_Subclass()
 {
     using (var c = new NSHttpCookie("name", "value")) {
         // we want to ensure we get the NSMutableDictionary even if we ask for (the base) NSDictionary
         var d = Runtime.GetNSObject <NSDictionary> (Messaging.IntPtr_objc_msgSend(c.Handle, Selector.GetHandle("properties")));
         Assert.That(d, Is.TypeOf <NSMutableDictionary> (), "NSMutableDictionary");
     }
 }
Exemplo n.º 17
0
 public void DotNetInteropMin()
 {
     // an invalid NSDictionary returns null from Objective-C but that
     // results in an 'empty' instance inside MonoTouch
     using (var cookie = new NSHttpCookie(new Cookie())) {
         Assert.That(cookie.Handle, Is.EqualTo(NativeHandle.Zero), "ctor");
     }
 }
Exemplo n.º 18
0
        void SetValueForPopditCookie(string key, string value)
        {
            NSHttpCookie cookie = GetPopditCookie();

            if (cookie != null)
            {
                cookie.SetValueForKey(NSObject.FromObject(value), (NSString)key);
            }
        }
Exemplo n.º 19
0
 public void NiceFourCtor()
 {
     using (NSHttpCookie cookie = new NSHttpCookie("iherd", "ulikecookies", "/", "yodawg.com")) {
         Assert.That(cookie.Name, Is.EqualTo("iherd"), "Name");
         Assert.That(cookie.Value, Is.EqualTo("ulikecookies"), "Value");
         Assert.That(cookie.Path, Is.EqualTo("/"), "Path");
         Assert.That(cookie.Domain, Is.EqualTo("yodawg.com"), "Domain");
     }
 }
Exemplo n.º 20
0
        private void LoadPageWithCookies()
        {
            var cookie = new NSHttpCookie(
                name: "test-xamarin-cookie",
                value: "test-xamarin-cookie-value",
                path: "/",
                domain: "127.0.0.1");

            webView.Configuration.WebsiteDataStore.HttpCookieStore.SetCookie(cookie, null);
            webView.LoadRequest(new NSUrlRequest(new NSUrl("http://127.0.0.1:5500/ProtectedWebSite/index.html")));
        }
Exemplo n.º 21
0
        public override void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action <WKNavigationResponsePolicy> decisionHandler)
        {
            NSHttpUrlResponse response = navigationResponse.Response as NSHttpUrlResponse;

            NSHttpCookie[] cookies = NSHttpCookie.CookiesWithResponseHeaderFields(response.AllHeaderFields, response.Url);

            foreach (NSHttpCookie cookie in cookies)
            {
                NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
            }

            decisionHandler(WKNavigationResponsePolicy.Allow);
        }
Exemplo n.º 22
0
        public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action <WKNavigationActionPolicy> decisionHandler)
        {
            if (Reference == null || !Reference.TryGetTarget(out FormsWebViewRenderer renderer))
            {
                return;
            }
            if (renderer.Element == null)
            {
                return;
            }

#if DEBUG
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                webView.Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookies((NSHttpCookie[] obj) => {
                    System.Diagnostics.Debug.WriteLine("*** DecidePolicy webView.Configuration.WebsiteDataStore");
                    for (var i = 0; i < obj.Length; i++)
                    {
                        var nsCookie = obj[i];
                        var domain   = nsCookie.Domain;
                        System.Diagnostics.Debug.WriteLine($"Domain={nsCookie.Domain}; Name={nsCookie.Name}; Value={nsCookie.Value};");
                    }
                });
            }
#endif
            if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                var headers          = navigationAction.Request.Headers as NSMutableDictionary;
                var cookieDictionary = NSHttpCookie.RequestHeaderFieldsWithCookies(NSHttpCookieStorage.SharedStorage.Cookies);
                foreach (var item in cookieDictionary)
                {
                    headers.SetValueForKey(item.Value, new NSString(item.Key.ToString()));
                }
            }
            var response = renderer.Element.HandleNavigationStartRequest(navigationAction.Request.Url.ToString());

            if (response.Cancel || response.OffloadOntoDevice)
            {
                if (response.OffloadOntoDevice)
                {
                    AttemptOpenCustomUrlScheme(navigationAction.Request.Url);
                }

                decisionHandler(WKNavigationActionPolicy.Cancel);
            }
            else
            {
                decisionHandler(WKNavigationActionPolicy.Allow);
                renderer.Element.Navigating = true;
            }
        }
Exemplo n.º 23
0
        async Task <List <NSHttpCookie> > GetCookiesFromNativeStore(string url)
        {
            NSHttpCookie[] _initialCookiesLoaded = null;
            if (Forms.IsiOS11OrNewer)
            {
                _initialCookiesLoaded = await Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookiesAsync();
            }
            else
            {
                // I haven't found a different way to get the cookies pre ios 11
                var cookieString = await WebView.EvaluateJavaScriptAsync("document.cookie");

                if (cookieString != null)
                {
                    CookieContainer extractCookies = new CookieContainer();
                    var             uri            = CreateUriForCookies(url);

                    foreach (var cookie in cookieString.Split(';'))
                    {
                        extractCookies.SetCookies(uri, cookie);
                    }

                    var extracted = extractCookies.GetCookies(uri);
                    _initialCookiesLoaded = new NSHttpCookie[extracted.Count];
                    for (int i = 0; i < extracted.Count; i++)
                    {
                        _initialCookiesLoaded[i] = new NSHttpCookie(extracted[i]);
                    }
                }
            }

            _initialCookiesLoaded = _initialCookiesLoaded ?? new NSHttpCookie[0];

            List <NSHttpCookie> existingCookies = new List <NSHttpCookie>();
            string domain = CreateUriForCookies(url).Host;

            foreach (var cookie in _initialCookiesLoaded)
            {
                // we don't care that much about this being accurate
                // the cookie container will split the cookies up more correctly
                if (!cookie.Domain.Contains(domain) && !domain.Contains(cookie.Domain))
                {
                    continue;
                }

                existingCookies.Add(cookie);
            }

            return(existingCookies);
        }
Exemplo n.º 24
0
        // returns the header for a cookie
        public static string GetHeaderValue(this NSHttpCookie cookie)
        {
            var header = new StringBuilder();

            AppendSegment(header, cookie.Name, cookie.Value);
            AppendSegment(header, NSHttpCookie.KeyPath.ToString(), cookie.Path.ToString());
            AppendSegment(header, NSHttpCookie.KeyDomain.ToString(), cookie.Domain.ToString());
            AppendSegment(header, NSHttpCookie.KeyVersion.ToString(), cookie.Version.ToString());

            if (cookie.Comment != null)
            {
                AppendSegment(header, NSHttpCookie.KeyComment.ToString(), cookie.Comment.ToString());
            }

            if (cookie.CommentUrl != null)
            {
                AppendSegment(header, NSHttpCookie.KeyCommentUrl.ToString(), cookie.CommentUrl.ToString());
            }

            if (cookie.Properties.ContainsKey(NSHttpCookie.KeyDiscard))
            {
                AppendSegment(header, NSHttpCookie.KeyDiscard.ToString(), null);
            }

            if (cookie.ExpiresDate != null)
            {
                // Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo)
                var dateStr = ((DateTime)cookie.ExpiresDate).ToUniversalTime().ToString("r", CultureInfo.InvariantCulture);
                AppendSegment(header, NSHttpCookie.KeyExpires.ToString(), dateStr);
            }

            if (cookie.Properties.ContainsKey(NSHttpCookie.KeyMaximumAge))
            {
                var timeStampString = (NSString)cookie.Properties[NSHttpCookie.KeyMaximumAge];
                AppendSegment(header, NSHttpCookie.KeyMaximumAge.ToString(), timeStampString);
            }

            if (cookie.IsSecure)
            {
                AppendSegment(header, NSHttpCookie.KeySecure.ToString(), null);
            }

            if (cookie.IsHttpOnly)
            {
                AppendSegment(header, "httponly", null);                  // Apple does not show the key for the httponly
            }
            return(header.ToString());
        }
        void LoadInternetContent()
        {
            if (Control == null || Element == null)
            {
                return;
            }

            var headers = new NSMutableDictionary();

            foreach (var header in Element.LocalRegisteredHeaders)
            {
                var key = new NSString(header.Key);
                if (!headers.ContainsKey(key))
                {
                    headers.Add(key, new NSString(header.Value));
                }
            }

            if (Element.EnableGlobalHeaders)
            {
                foreach (var header in FormsWebView.GlobalRegisteredHeaders)
                {
                    var key = new NSString(header.Key);
                    if (!headers.ContainsKey(key))
                    {
                        headers.Add(key, new NSString(header.Value));
                    }
                }
            }

            if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                var cookieDictionary = NSHttpCookie.RequestHeaderFieldsWithCookies(NSHttpCookieStorage.SharedStorage.Cookies);
                foreach (var item in cookieDictionary)
                {
                    headers.SetValueForKey(item.Value, new NSString(item.Key.ToString()));
                }
            }

            var url     = new NSUrl(Element.Source);
            var request = new NSMutableUrlRequest(url)
            {
                Headers = headers
            };

            Control.LoadRequest(request);
        }
Exemplo n.º 26
0
        NSHttpCookie GetPopditCookie()
        {
            // Get the cookies.
            NSHttpCookie[] cookies = NSHttpCookieStorage.SharedStorage.Cookies;
            // Find the Popdit cookie.
            NSHttpCookie cookie = null;

            foreach (NSHttpCookie c in cookies)
            {
                if (c.Name == "Popdit")
                {
                    cookie = c;
                }
                break;
            }
            return(cookie);
        }
            public override void DecidePolicy(WKWebView webView,
                                              WKNavigationResponse navigationResponse,
                                              Action <WKNavigationResponsePolicy> decisionHandler)
            {
                if (navigationResponse.Response is NSHttpUrlResponse rsp)
                {
                    var cookie = NSHttpCookie.CookiesWithResponseHeaderFields(rsp.AllHeaderFields, rsp.Url);
                    foreach (var c in cookie)
                    {
                        webView.Configuration.WebsiteDataStore.HttpCookieStore.SetCookieAsync(c);
                    }

                    var target = owner.eventsHandler.CurrentAction;
                    if (target?.Type == WebViewActionType.Download)
                    {
                        bool startDownload = false;
                        if (!string.IsNullOrEmpty(target.MimeType))
                        {
                            startDownload = rsp.AllHeaderFields.TryGetValue(new NSString("Content-Type"), out var contentType) &&
                                            (NSString)contentType == target.MimeType;
                        }
                        else if (rsp.AllHeaderFields.TryGetValue(new NSString("X-Download-Options"), out var downloadOptions) &&
                                 (NSString)downloadOptions == "noopen")
                        {
                            startDownload = true;
                        }
                        else if (rsp.AllHeaderFields.TryGetValue(new NSString("Content-Disposition"), out var contentDisposition) &&
                                 contentDisposition.ToString().StartsWith("attachment;", StringComparison.Ordinal))
                        {
                            startDownload = true;
                        }
                        else if ((Uri)rsp.Url == target.Uri)
                        {
                            startDownload = true;
                        }
                        if (startDownload)
                        {
                            decisionHandler(WKNavigationResponsePolicy.Cancel);
                            StartDownload(rsp.Url, target);
                            return;
                        }
                    }
                }

                decisionHandler(WKNavigationResponsePolicy.Allow);
            }
Exemplo n.º 28
0
        public void DotNetInteropCommon()
        {
            var c = new Cookie("name", "key", "path", "domain");

            using (NSHttpCookie cookie = new NSHttpCookie(c)) {
                Assert.That(cookie.Name, Is.EqualTo("name"), "Name");
                Assert.That(cookie.Value, Is.EqualTo("key"), "Value");
                Assert.That(cookie.Path, Is.EqualTo("path"), "Path");
                Assert.That(cookie.Domain, Is.EqualTo("domain"), "Domain");
                // defaults
                Assert.Null(cookie.Comment, "Comment");
                Assert.Null(cookie.CommentUrl, "CommentUrl");
                Assert.Null(cookie.ExpiresDate, "ExpiresDate");
                Assert.False(cookie.IsHttpOnly, "IsHttpOnly");
                Assert.False(cookie.IsSecure, "IsSecure");
                Assert.True(cookie.IsSessionOnly, "IsSessionOnly");                  // discard
                Assert.That(cookie.PortList.Length, Is.EqualTo(0), "PortList");
                Assert.NotNull(cookie.Properties, "Properties");
                Assert.That(cookie.Version, Is.EqualTo((nuint)0), "Version");
            }
        }
Exemplo n.º 29
0
        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));
        }
        protected void SetCookies(Uri uri, string v)
        {
            CachedCookieStore.Clear();
#if __DROID__
            CookieManager.Instance.SetCookie(uri.ToString(), v);
            try
            {
                CookieManager.Instance.Flush();
            }
            catch {
            }
#endif
#if __IOS__
            var cookieParser = new CookieContainer();
            cookieParser.SetCookies(uri, v);

            foreach (System.Net.Cookie cookie in cookieParser.GetCookies(uri))
            {
                NSHttpCookie nsc = new NSHttpCookie(cookie);
                NSHttpCookieStorage.SharedStorage.SetCookie(nsc);
            }
#endif
        }
Exemplo n.º 31
0
        string GetValueForPopditCookieKey(string key)
        {
            string value = "";

            try
            {
                NSHttpCookie cookie = GetPopditCookie();
                // Get the "value" string from the cookie, something like "key1=xyz&key2=abc&key3=pdq".
                string cookieValueString = (NSString)cookie.ValueForKey(new NSString("value")).ToString();
                // Split the value string into key-value substrings, like "key1=xyz".
                string[] cookieKeyValuePairs = cookieValueString.Split('&');
                // Find the key-value pair for the given key, like "SecurityToken=JWDCh*34fd-3h42".
                string desiredKeyValuePair = "";
                int    i = 0;
                do
                {
                    desiredKeyValuePair = cookieKeyValuePairs[i++];
                }while (!desiredKeyValuePair.Contains(key));
                // Parse out the value from the SecurityToken key-value pair and initialize the security token in this object.
                value = desiredKeyValuePair.Split('=')[1];
            }
            catch { } // No cookie, no Popdit cookie, no value string, no instance of desired key, no value for desired key - whatever ...
            return(value);
        }