I have a UIWebView which Authenticates a user. I want to enable single Sign on. For this I want to store the cookies when the user is first authenticated and then the next time he starts the app, the cookies should automatically be passed to the UIWebView and authenticate the user without him entering his credentials again.
Iam doing something like below to use the UIWebView
var uri = new Uri(AuthUrl);
var nsurl = new NSUrl(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped));
wvLogin.LoadRequest(new NSUrlRequest(nsurl));
CookieManager.cs
public static void SaveCookies()
{
var cookieData = new NSMutableArray ();
var cookieStorage = NSHttpCookieStorage.SharedStorage;
foreach (var nscookie in cookieStorage.Cookies) {
var cookieDictionary = new NSMutableDictionary ();
cookieDictionary.Add (NSHttpCookie.KeyName, new NSString (nscookie.Name));
cookieDictionary.Add (NSHttpCookie.KeyValue,new NSString ( nscookie.Value));
cookieDictionary.Add (NSHttpCookie.KeyDomain,new NSString ( nscookie.Domain));
cookieDictionary.Add (NSHttpCookie.KeyPath, new NSString (nscookie.Path));
cookieDictionary.Add (NSHttpCookie.KeySecure, new NSString ( nscookie.IsSecure.ToString()));
cookieDictionary.Add (NSHttpCookie.KeyVersion, new NSString (nscookie.Version.ToString()));
if (nscookie.ExpiresDate != null) {
cookieDictionary.Add (NSHttpCookie.KeyExpires, nscookie.ExpiresDate);
}
cookieData.Add (cookieDictionary);
}
cookieData.WriteToFile (StoragePath(), true);
}
public static string StoragePath()
{
//var paths = NSSearchPath.GetDirectories (NSSearchPathDirectory.LibraryDirectory, NSUserDomainMask, true);
var paths = NSSearchPath.GetDirectories(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User, true);
return paths [0].ToString ();
}
public static void DeleteCookies()
{
NSHttpCookieStorage cookieStorage = NSHttpCookieStorage.SharedStorage;
foreach (var nscookie in cookieStorage.Cookies)
{
cookieStorage.DeleteCookie(nscookie);
}
NSUserDefaults.StandardUserDefaults.Synchronize ();
}
public static void LoadCookies()
{
var cookies = NSMutableArray.FromFile (StoragePath());
var cookieStorage = NSHttpCookieStorage.SharedStorage;
foreach (var nscookie in cookieStorage.Cookies)
{
cookieStorage.SetCookie(nscookie);
}
}
LoginScreen.cs
void wvLogin_LoadFinished(object sender, EventArgs e)
{
int redirectCount = 0;
redirect = System.Net.WebUtility.UrlDecode(wvLogin.Request.Url.AbsoluteString);
// Do some stuff
CookieManager.SaveCookies();
}
}
else
{
AppDelegate.Logout();
}
}
}
How can I achieve this? Any help is appreciated as Iam new to iOS and Xamarin.