Accessing WebView cookies in WinRT

Uncategorized

8 years ago

In my recent Windows 8.1 app project I needed to take advantage of ASP.NET Identity to authenticate in my ASP.NET Web API service. Because Identity offers social (external) logins on top of classic login flow, I decided to integrate them as well. Unfortunately the authentication process required the use of cookies, which needed to be forwarded to the registration endpoint to complete the registration process of a new user. Because the process itself is initiated in a WebView control, we need to obtain the resulting cookies. But WebView does not expose any properties to access them. What can we do? It turns out it is possible to access the collection of cookies globally, without direct access to the WebView control. First step is to create an instance of the HttpBaseProtocolFilter class and access its CookieManager property. HttpCookieManager has a few useful methods:

  • GetCookies - returns a HttpCookieCollection of cookies associated with a given URI
  • SetCookie - sets a cookie
  • DeleteCookie - deletes a cookie

To list all the cookies associated with our URI we can then just enumerate the HttpCookieCollection we get from GetCookies method:

HttpBaseProtocolFilter myFilter = new HttpBaseProtocolFilter();
var cookieManager = myFilter.CookieManager;
HttpCookieCollection myCookieJar = cookieManager.GetCookies( new Uri( "http://localhost:33633/" ) );
foreach ( HttpCookie c in myCookieJar )
{
   Debug.WriteLine( c.Name );
   Debug.WriteLine( c.Value );
}