net access browser Cookie of includes HttpOnly instance sharing

  • 2020-07-21 07:26:55
  • OfStack

1. Interface file


using System; 
using System.ComponentModel; 
using System.Net; 
using System.Runtime.InteropServices; 
using System.Security; 
using System.Security.Permissions; 
using System.Text; 

namespace CookieHandler 
{ 
    internal sealed class INativeMethods 
    { 
        #region enums 

        public enum ErrorFlags 
        { 
            ERROR_INSUFFICIENT_BUFFER = 122, 
            ERROR_INVALID_PARAMETER = 87, 
            ERROR_NO_MORE_ITEMS = 259 
        } 

        public enum InternetFlags 
        { 
            INTERNET_COOKIE_HTTPONLY = 8192, //Requires IE 8 or higher      
            INTERNET_COOKIE_THIRD_PARTY = 131072, 
            INTERNET_FLAG_RESTRICTED_ZONE = 16 
        } 

        #endregion 

        #region DLL Imports 

        [SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("wininet.dll", EntryPoint = "InternetGetCookieExW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] 
        internal static extern bool InternetGetCookieEx([In] string Url, [In] string cookieName, [Out] StringBuilder cookieData, [In, Out] ref uint pchCookieData, uint flags, IntPtr reserved); 

        #endregion 
    } 
} 

2. Get the cookie class


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Net; 
using System.Runtime.InteropServices; 
using System.Security; 
using System.Security.Permissions; 
using System.Text; 

namespace CookieHandler 
{ 
    /// <SUMMARY></SUMMARY> 
    ///  achieve WebBrowser The complete Cookie .  
    ///  Because by default webBrowser1.Document.Cookie Take less than HttpOnly the Cookie 
    /// IE7 Are not compatible, IE8 Ok, other unknowns  
    /// 
    public class FullWebBrowserCookie 
    { 
        public static Dictionary<string, string> GetCookieList(Uri uri, bool throwIfNoCookie) 
        { 
            Dictionary<string, string> dict = new Dictionary<string, string>(); 
            string cookie = GetCookieInternal(uri, throwIfNoCookie); 
            Console.WriteLine("FullWebBrowserCookie -  all cookie:" + cookie); 
            string[] arrCookie = cookie.Split(';'); 
            foreach (var item in arrCookie) 
            { 
                string[] arr = item.Split('='); 
                string key = arr[0].Trim(); 
                string val = ""; 
                if (arr.Length >= 2) 
                { 
                    val = arr[1].Trim(); 
                } 

                if (!dict.ContainsKey(key)) 
                { 
                    dict.Add(key, val); 
                } 
            } 
            Console.WriteLine("FullWebBrowserCookie - cookie Recorded in dict , a total of " + dict.Count.ToString() + " item "); 

            return dict; 
        } 

        public static string GetCookieValue(string key, Uri uri, bool throwIfNoCookie) 
        { 
            Console.WriteLine("GetCookieValue"); 
            Dictionary<string, string> dict = GetCookieList(uri, throwIfNoCookie); 

            if (dict.ContainsKey(key)) 
            { 
                return dict[key]; 
            } 
            return ""; 
        } 

        [SecurityCritical] 
        public static string GetCookieInternal(Uri uri, bool throwIfNoCookie) 
        { 
            Console.WriteLine("GetCookieInternal"); 

            uint pchCookieData = 0; 
            string url = UriToString(uri); 
            uint flag = (uint)INativeMethods.InternetFlags.INTERNET_COOKIE_HTTPONLY; 

            //Gets the size of the string builder      
            if (INativeMethods.InternetGetCookieEx(url, null, null, ref pchCookieData, flag, IntPtr.Zero)) 
            { 
                pchCookieData++; 
                StringBuilder cookieData = new StringBuilder((int)pchCookieData); 

                //Read the cookie      
                if (INativeMethods.InternetGetCookieEx(url, null, cookieData, ref pchCookieData, flag, IntPtr.Zero)) 
                { 
                    DemandWebPermission(uri); 
                    return cookieData.ToString(); 
                } 
            } 

            int lastErrorCode = Marshal.GetLastWin32Error(); 

            if (throwIfNoCookie || (lastErrorCode != (int)INativeMethods.ErrorFlags.ERROR_NO_MORE_ITEMS)) 
            { 
                throw new Win32Exception(lastErrorCode); 
            } 

            return null; 
        } 

        private static void DemandWebPermission(Uri uri) 
        { 
            string uriString = UriToString(uri); 

            if (uri.IsFile) 
            { 
                string localPath = uri.LocalPath; 
                new FileIOPermission(FileIOPermissionAccess.Read, localPath).Demand(); 
            } 
            else
            { 
                new WebPermission(NetworkAccess.Connect, uriString).Demand(); 
            } 
        } 

        private static string UriToString(Uri uri) 
        { 
            if (uri == null) 
            { 
                throw new ArgumentNullException("uri"); 
            } 

            UriComponents components = (uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString); 
            return new StringBuilder(uri.GetComponents(components, UriFormat.SafeUnescaped), 2083).ToString(); 
        } 
    } 
} 


Related articles: