Set cookie in Xamarin Android WebView - cookies

In Xamarin Android SDK 30, when trying to set webview cookie does not work.
string cookieString = string.Format("{0}={1}; path=/;domain={2}; secure; ", Strings.SessionCookie, encryptedCookie, "value");
if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
CookieManager.Instance.SetAcceptThirdPartyCookies(webView, true);
}
else
{
CookieManager.Instance.SetAcceptCookie(true); //this function doesn't work from lollipop(API21) and above
}
CookieManager.Instance.SetCookie(RootCookieDomain, cookieString);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.DomStorageEnabled = true;
webView.LoadUrl(Link);
The above code works perfectly in SDK 29 but as soon as its switched to 30 it stops working and cookie is not being set.

I set the cookie with the code below. It works on API30.
Xaml:
<WebView x:Name="MyWebview" WidthRequest="400" HeightRequest="500"></WebView>
<Button Text="click to load" Clicked="Button_Clicked"></Button>
Code:
private void Button_Clicked(object sender, EventArgs e)
{
CookieContainer cookieContainer = new CookieContainer();
Uri uri = new Uri("https://dotnet.microsoft.com/apps/xamarin", UriKind.RelativeOrAbsolute);
Cookie cookie = new Cookie
{
Name = "XamarinCookie",
Expires = DateTime.Now.AddDays(1),
Value = "My cookie",
Domain = uri.Host,
Path = "/"
};
cookieContainer.Add(uri, cookie);
MyWebview.Cookies = cookieContainer;
MyWebview.Source = new UrlWebViewSource { Url = uri.ToString() };
}

Related

Trying to get a cookie value which I set on ARCGIS online but not getting any value back?

I am trying to set a cookie in ESRI Arcgis online using ESRI runtime SDK for .net v100.
var cookie = new CookieHeaderValue("customCookie", cred.Token);
var response = Request.CreateResponse(HttpStatusCode.OK, new {
token = cred.Token,
expires = cred.ExpirationDate
});
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
Now when I try to retrieve that cookie later on in subsequent requests using below I get null.
CookieHeaderValue cookie = context.Request.Headers.GetCookies("customCookie").FirstOrDefault();
I am wondering if there is another way to get the cookie which I set back?
Are you using v100?
If yes, you can try the following code:
ArcGISHttpClientHandler.HttpRequestBegin += (sender, request) =>
{
var cookieContainer = ((System.Net.Http.HttpClientHandler)sender).CookieContainer;
var cookies = cookieContainer.GetCookies(request.RequestUri);
var customCookie = new Cookie("customCookie", "someValue") { Domain = request.RequestUri.Host };
bool foundCookie = false;
foreach (Cookie cookie in cookies)
{
if (cookie.Name == customCookie.Name)
{
foundCookie = true;
break;
}
}
if (!foundCookie)
cookieContainer.Add(customCookie);
};
ArcGISHttpClientHandler has an event HttpRequestBegin which is invoked on every request. You can use CookieContainer.GetCookies and Add to retrieve/add cookies.

Couldn't set authentication cookie lifetime - IdentityServer4

I am trying to set the IdentityServer4 authentication cookie lifetime.
This is my client configuration :
// OpenID Connect hybrid flow and client credentials client (MVC)
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
IdentityTokenLifetime = 120,
AccessTokenLifetime = 120,
AuthorizationCodeLifetime = 120,
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
RedirectUris = new List<string>
{
"http://localhost:5002/signin-oidc"
},
PostLogoutRedirectUris = new List<string>
{
"http://localhost:5002"
},
AllowedScopes = new List<string>
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
StandardScopes.OfflineAccess.Name,
"api1"
}
}
and my Configure method in the mvc client is
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticChallenge = true,
ExpireTimeSpan = System.TimeSpan.FromSeconds(120),
SlidingExpiration = false
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
ClientId = "mvc",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "api1", "offline_access" },
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = true
});
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
I'm using the below sample from IdentityServer4 samples to learn IdentityServer4.
IdentityServer4.Samples/Quickstarts/5_HybridFlowAuthenticationWithApiAccess
I have already set the cookie expire time, access token life time, identity token life time and authorization code life time. But still the cookie life time is showing as session in the browser. Please see the below image
Am I missed any setting to do?
Any help is greatly appreciated.

Call a UI controller with FedAuth cookie from SAML token

We're trying to automate some integrated tests. So we'd like to be able to programatically call the UI controllers in order to be as clause as what the reel users do. We don't want to use a UI test suite for different reasons.
Problem is that we are using SSO Windows authentication with the WS-Federation security with WIF. In configuration, we use passiveRedirectEnabled="true" so that every time the session cookie is absent, invalid or expired, the page gets redirected to the AD FS STS endpoint ("/adfs/ls/"). The result is again redirected back to page specify in the "reply" attribute in the Web.config file.
When I look in Fiddler, I clearly see the second redirect (coming back from the AD FS STS) with a 302 status returns a "Set-Cookie : FedAuth=77u/PD94bWwg..." instruction to the browser. The the call is made to the reply page with the FedAuth cookie and everything is OK from there.
Is there a way to emulate this behavior and be able to call the UI controller with the correct FedAuth cookie ? No SharePoint please, this has nothing to do with it.
I was finally able to reproduce the steps from what I saw in Fiddler to mimic the browser. I'll let the code here, hoping it can help some of you along the way. It's not very clean, it's more in a POC mode but it still can help. Note that on some requests I had to allow the automatic redirection an some others I had to prevent it.
Credits to my colleague Dominique Pothier who helped me a lot on that one.
//First request to the secured site
var request =
(HttpWebRequest)WebRequest.Create("https://mysite.mycompany.ca/");
request.Method = "GET";
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.AllowAutoRedirect = false;
var httpResponse = (HttpWebResponse)request.GetResponse();
//Redirects to the STS based on the response from the first call, posting the ws-federations infos along
request =
(HttpWebRequest)WebRequest.Create(httpResponse.Headers["Location"]);
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Host = "sts.mycompany.ca";
request.AllowAutoRedirect = true;
request.UserAgent =
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
var nameValueCollection = new NameValueCollection { { "Cache-Control", "max-age=0" } };
request.Headers.Add(nameValueCollection);
nameValueCollection = new NameValueCollection { { "Upgrade-Insecure-Requests", "1" } };
request.Headers.Add(nameValueCollection);
nameValueCollection = new NameValueCollection { { "Accept-Encoding", "gzip, deflate, sdch" } };
request.Headers.Add(nameValueCollection);
nameValueCollection = new NameValueCollection { { "Accept-Language", "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4" } };
request.Headers.Add(nameValueCollection);
httpResponse = (HttpWebResponse)request.GetResponse();
//Parse the response to get ws-federation infos
var responseStream = new StreamReader(httpResponse.GetResponseStream());
var responseData = responseStream.ReadToEnd();
var xmlReader = XmlReader.Create(new StringReader(responseData));
var wa = "";
var wresult = "";
var wctx = "";
while (xmlReader.Read())
{
if (xmlReader.GetAttribute("name") == "wa")
wa = xmlReader.GetAttribute("value");
if (xmlReader.GetAttribute("name") == "wresult")
wresult = xmlReader.GetAttribute("value");
if (xmlReader.GetAttribute("name") == "wctx")
wctx = xmlReader.GetAttribute("value");
}
httpResponse.Close();
//Redirects to the controller method we want to hit
request =
(HttpWebRequest)WebRequest.Create("https://mysite.mycompany.ca/Home/GetStates");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
//Add the cookie container to the response so that we can get the FedAuth cookie after the response
request.CookieContainer = new CookieContainer();
//Add the ws-federation infos from the last http request to the body of the new request
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
if (wa != null)
{
var waEncoded = HttpUtility.UrlEncode(wa);
var wresultEncoded = HttpUtility.UrlEncode(wresult);
var wctxEncoded = HttpUtility.UrlEncode(wctx);
var urlEncoded = "wa=" + waEncoded + "&wresult=" + wresultEncoded + "&wctx=" + wctxEncoded;
streamWriter.Write(urlEncoded);
streamWriter.Flush();
streamWriter.Close();
}
}
request.Referer = httpResponse.ResponseUri.OriginalString;
httpResponse = (HttpWebResponse)request.GetResponse();
var cookieContainer = request.CookieContainer;
//Use the FedAuth cookie that we got from last http call and add it to a new request to the controller and voila !
request =
(HttpWebRequest)WebRequest.Create("https://mysite.mycompany.ca/Home/GetStates");
request.Method = "GET";
nameValueCollection = new NameValueCollection { { "X-Requested-With", "XMLHttpRequest" } };
request.Headers.Add(nameValueCollection);
//Add the FedAuthCookie from last request
request.CookieContainer = cookieContainer;
request.Referer = "https://proacces-dev1.universitas.ca/";
httpResponse = (HttpWebResponse)request.GetResponse();
responseStream = new StreamReader(httpResponse.GetResponseStream());
responseData = responseStream.ReadToEnd();
Console.WriteLine(responseData);
Console.ReadLine();

Cannot logout from facebook in a windows8 phone app using phonegap. how can I solve this?

Hello guys I am implementing logout from facebook functionality in my windows 8 phone application. By using the given below code I am able to logout from the facebook but when I again click on the facebook login button, then it automatically logged in without asking for the email and password.
var redir_url1 = "http://www.facebook.com/connect/logout_success.html";
//redir_url1 is used to redirect it
alert("inside prototype logout");
//store the value of accesstoken locally in finalAccessTokens
var finalAccessToken1 = window.localStorage.getItem("finalAccessTokens");
alert("finalAccessToken1" + finalAccessToken1);
var authorize_url = "https://www.facebook.com/logout.php?confirm=1";
//alert("authorize_url" + authorize_url);
authorize_url += "next=" + redir_url1;
authorize_url += "&access_token=" + finalAccessToken1;
alert("logout url: " + authorize_url);
resetSession();
showWebPage1(authorize_url);
//call a function to open the webpage
}
function showWebPage1(loc) {
alert("logout loc" + loc);
// var locs=this.loc;
cordova.exec(success1, error1, "InAppBrowser", "ShowInAppBrowser", loc);
}
function success1(e) {
alert("logout success");
//var accessToken = window.localStorage.getItem("finalAccessTokens");
// var url = 'https://graph.facebook.com/me?access_token=' + accessToken;
//localStorage.removeItem(cookies);
//localStorage.removeItem(finalAccessTokens);
// closeAndClearTokenInformation;
//ClearInternetCacheAsync();
alert("After removing access token" + `enter code here`window.localStorage.getItem("finalAccessTokens"));
//finalAccessTokens is used to locally store the value of access token
window.localStorage.clear();
alert("success" + JSON.stringify(e));
var successLogout = JSON.stringify(e);
if ((successLogout.indexOf('https://www.facebook.com/home.php') != -1) &&
(successLogout.indexOf('loadstop') != -1)) {
alert("sss in close");
cordova.exec(null, null, "InAppBrowser", "close", []);
alert("after the handle is closed.....");
this.resetSession();
//to reset the session
}
}
function error1() {
alert("err");
}
FBConnect.prototype.resetSession = function () {
alert("session reset");
this.status = "unknown";
this.session = {};
alert("clear access token/////");
this.session.access_token = null;
alert(this.session.access_token);
this.session.expires = new Date().valueOf() - 1000;
this.session.secret = null;
this.session.session_key = null;
this.session.sig = null;
this.session.uid = null;
alert(this.session.uid);
}
You have to remove WebBrowser cookies after you logout. I am not sure how you can do that using PhoneGap, but in a C#/XAML app you can remove them like this:
await new WebBrowser().ClearCookiesAsync();

clear cookie container in WebRequest

I'm using the WebRequest object to post data to a login page, then post data to a seperate page on the same site. I am instantiating a CookieContainer and assigning it to the WebRequest object so that the cookies are handled. The problem is that I do not want to retain the cookie after I post data to the other page. How can I delete that cookie?
private CookieContainer cookie_m;
protected CookieContainer CookieContainer
{
get
{
if (cookie_m == null)
{
cookie_m = new CookieContainer();
}
return cookie_m;
}
set
{
cookie_m = value;
}
}
protected virtual void SetData(WebRequest request, string sData)
{
if (!String.IsNullOrEmpty(sData))
{
byte[] binPostData = System.Text.Encoding.ASCII.GetBytes(sData);
request.ContentLength = binPostData.Length;
System.IO.Stream sRequest = request.GetRequestStream();
try
{
sRequest.Write(binPostData, 0, binPostData.Length);
}
finally
{
sRequest.Close();
}
}
}
private HttpWebRequest GetNewRequest(string sUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl);
request.CookieContainer = this.CookieContainer;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
public override void Submit()
{
//Login
HttpWebRequest request = GetNewRequest("http://mytest/login.asp");
base.SetData(request, "action=validate_login&login=test&password=test");
WebResponse response = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
string sResponse = sr.ReadToEnd();
//Entry screen
request = GetNewRequest("http://mytest/CustCreate.asp");
base.SetData(request, "Site=xyz&Cust=test");
response = request.GetResponse();
sr = new System.IO.StreamReader(response.GetResponseStream());
sResponse = sr.ReadToEnd();
//Sutmit
request = request = GetNewRequest("http://mytest/CustCreate.asp");
base.SetData(request, "Site=xyz&mydatahere&B1=Submit");
response = request.GetResponse();
sr = new System.IO.StreamReader(response.GetResponseStream());
sResponse = sr.ReadToEnd();
//How to delete cookies that have been saved?
}
To delete a cookie, you need to set the expiration date on it to a date in the past. This tells the browser it's expired and the browser will delete it.
Here's an example from msdn on how to do this in C# (not sure which language you're using).
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}