Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put cookie on a WebView in Xamarin

I have the following plan in my Xamarin Project:

  • The user enters his username and password on the MainPage.
  • If data correct (API exists), navigate to a WebView and automatically login the user on this page.

The existing API (not public) delivers a System.Net.CookieCollection.

How can I realise my idea, using a POST-Request with those cookies? Here's my base:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WebPage : ContentPage
{
    public WebPage(string url, CookieCollection cookies)
    {
        InitializeComponent();
        BindingContext = new MainPageViewModel();
        MyWebView.Source = "https://" + url;

    }
}

Kind regards, localhorst27

like image 851
localhorst27 Avatar asked Mar 17 '17 09:03

localhorst27


1 Answers

You will have to create a custom renderer for the WebView on both Android and iOS. That way you'll be able to inject the cookies into the Android WebView and iOS UIWebView. If you are not familiar with them, start here: Introduction to Custom Renderers

When you're familiar with how renderers work, follow this post by Christine Blanda on Xamarin forums: Setting Cookies in a WebView

I'll also post the code here to make sure it's preserved in case the original post goes down.

Android OnElementChanged

var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.RemoveAllCookie();
var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
for (var i = 0; i < cookies.Count; i++)
{
    string cookieValue = cookies[i].Value;
    string cookieDomain = cookies[i].Domain;
    string cookieName = cookies[i].Name;
    cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
}

iOS OnElementChanged

// Set cookies here
var cookieUrl = new Uri(AppInfo.URL_BASE);
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
    cookieJar.DeleteCookie(aCookie);
}

var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies = 
                   (from object jCookie in jCookies 
                    where jCookie != null 
                    select (Cookie) jCookie 
                    into netCookie select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
like image 128
Timo Salomäki Avatar answered Nov 12 '22 15:11

Timo Salomäki