c# Get httponly cookie

試著忘記壹切 提交于 2019-11-27 08:15:48

问题


How can i get a httponly cookie in a httpwebresponse ? Habitually i use a CookieContainer to get the cookies in a httpwebresponse, but it doesnt work with httponly cookie.

Is there an other way to catch them ?


回答1:


Yes, it is possible to retrieve a HTTPOnly cookie, for instance from a client program using the "InternetGetCookieEx" function in the "Wininet.dll". You must use PInvoke code like this :

/// <summary>
/// WinInet.dll wrapper
/// </summary>
internal static class CookieReader
{
    /// <summary>
    /// Enables the retrieval of cookies that are marked as "HTTPOnly". 
    /// Do not use this flag if you expose a scriptable interface, 
    /// because this has security implications. It is imperative that 
    /// you use this flag only if you can guarantee that you will never 
    /// expose the cookie to third-party code by way of an 
    /// extensibility mechanism you provide. 
    /// Version:  Requires Internet Explorer 8.0 or later.
    /// </summary>
    private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetGetCookieEx(
        string url,
        string cookieName,
        StringBuilder cookieData,
        ref int size,
        int flags,
        IntPtr pReserved);

    /// <summary>
    /// Returns cookie contents as a string
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string GetCookie(string url)
    {
        int size = 512;
        StringBuilder sb = new StringBuilder(size);
        if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
        {
            if (size < 0)
            {
                return null;
            }
            sb = new StringBuilder(size);
            if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
            {
                return null;
            }
        }
        return sb.ToString();
    }
}

The code is from MSDN.

I hope that helps !




回答2:


You cannot retrieve HTTPOnly cookies from the CookieContainer.

from MSDN

...You must always create a CookieContainer to send with a request if you want cookies to be returned on the response. This is also true for HTTPOnly cookies, which you cannot retrieve.



来源:https://stackoverflow.com/questions/3062925/c-sharp-get-httponly-cookie

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!