HttpWebResponse contains no cookies - cookies

I'm using HTTPWebRequest/HTTPWebResponse to interact with the site (www.lockerz.com). So, I authenticate on the site:
HttpWebRequest webRequest = (HttpWebRequest) HttpWebRequest.Create("http://www.lockerz.com/auth/login");
byte[] bytes = Encoding.ASCII.GetBytes("handle=" + textBoxEmail.Text + "&password=" + textBoxPassword.Text);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
Then I get the response:
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
I'm watching the requests\responses using Charles and it says that in the response there must be cookies, but when I try to make a list of the cookies I get it says that there are no cookies!
foreach(Cookie c in webResponse.Cookies) {
writeToLog("Cookie Name: " + c.Name + " Value: " + c.Value);
cc.Add(c);
}
I've tried adding a CookieContainer but it doesn't work anyway.

This may apply here, I have had this problem with sessions, so I will assume the same for cookies.
You are making a call to: http://www.lockerz.com/auth/login. But if a person goes to a page without the "www." part of the url, then their cookies won't survive being sent to the "www." site, because they are different sites (as far as the cookies are concerned).
I would just make the request to "/auth/login", that way, it won't matter what the user has as the url in their browser.
Hope this works.

Related

How do i clear cookies in Soap UI?

When i call a webservice which sends response with "Set-Cookie" header, soapui caches the cookies for subsequent calls. How do i clear these cookies on subsequent calls?
Or is there a way to "not-accept" cookies from the endpoints in the response?
I am using free Soap UI 4.5.0
Check out this post on eviware's forum one of the responses show how to clear cookies
I read the link from Abhishek in another answer to begin with, and found my answer on this link:
For anyone who is looking for answer, here is what i am using now:
Basically, you have to create a testcase with the requests that you want to run, and you will get a Script editor in TestSteps, where you can use the following groovy script.
import com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport
def myCookieStore = HttpClientSupport.getHttpClient().getCookieStore()
def myCookies = myCookieStore.getCookies()
// find the session cookie
def sessionCookie
myCookies.each {
// print all of them
log.info(it.name + " = " + it.value)
if (it.name == "JSESSIONID"){
sessionCookie = it
}
}
// if you want to update the cookie value
// sessionCookie.value = "new cookie value here..."
// deleting all cookies
myCookieStore.clear()
// to delete only specific
//if (sessionCookie != null) {
// sessionCookie.expiryDate = new Date()-1 // yesterday
// myCookieStore.clearExpired(new Date()-1)
//}
// check if the cookies are really removed
myCookies = myCookieStore.getCookies()
log.info("After Removing Session Cookie");
myCookies.each {
// print all of them
log.info(it.name + " = " + it.value)
}
// if you want to create your own cookie
//import org.apache.http.impl.Cookie.BasicClientCookie
//def myNewCookie = new BasicClientCookie("cookie_name", "cookie_value")
//myNewCookie.version = 1
//myNewCookie.domain = "qa.test"
//myCookieStore.addCookie(myNewCookie)
// or from another cookie
//def myNewCookie = new BasicClientCookie("cookie_name", interestingCookie.value)

Download data from internet page with WebClient but need to be logged on

I download the HTML from a webpage:
WebClient client = new WebClient();
DateTime dtStart = DateTime.Now;
string site = "http://www.google.de";
string result = client.DownloadString(site);
DateTime dtEnd = DateTime.Now;
richTests.Text = richTests.Text + result;
webBrowser1.DocumentText = result;
webBrowser1.ScriptErrorsSuppressed = true;
TimeSpan span = dtEnd - dtStart;
WriteLog("Seitenaufruf: " + site);
WriteLog("Time: " + span.Seconds.ToString() + "." + span.Milliseconds.ToString());
Now I have the same code on a internet site with a login validation.
I have a PHPSESSION in my Cookie from Firefox that I can use, so I only need a TextBox for inserting this - the problem here: How to give the WebClient client the PHPSESSION with a cookie - can a WebClient sotre a cookie before sending the DownloadString-Request?
You can read and write headers from the WebClient object. For example:
client.Headers.Add(HttpRequestHeader.Cookie, "cookies");
More info here: http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx

How can I get HttpOnly cookies in Windows Phone 8?

I am working in a Windows Phone 8 PCL project. I am using a 3rd party REST API and I need to use a few HttpOnly cookies originated by the API. It seems like getting/accessing the HttpOnly cookies from HttpClientHandler's CookieContainer is not possible unless you use reflection or some other backdoor.
I need to get these cookies and send them in subsequent requests otherwise I am not going to be able to work with this API - how can I accomplish this? Here is what my current request code looks like:
Thanks in advance.
//Some request
HttpRequestMessage request = new HttpRequestMessage();
HttpClientHandler handler = new HttpClientHandler();
//Cycle through the cookie store and add existing cookies for the susbsequent request
foreach (KeyValuePair<string, Cookie> cookie in CookieManager.Instance.Cookies)
{
handler.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value));
}
//Send the request asynchronously
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
//Parse all returned cookies and place in cookie store
foreach (Cookie clientcookie in handler.CookieContainer.GetCookies(request.RequestUri))
{
if (!CookieManager.Instance.Cookies.ContainsKey(clientcookie.Name))
CookieManager.Instance.Cookies.Add(clientcookie.Name, clientcookie);
else
CookieManager.Instance.Cookies[clientcookie.Name] = clientcookie;
}
HttpClient httpClient = new HttpClient(handler);
The HttpOnly cookie is inside the CookieContainer, it's only that is not exposed. If you set the same instance of that CookieContainer to the next request it will set the hidden cookie there (as long as the request is made to the same site the cookie specifies).
That solution will work until you need to serialize and deserialize the CookieContainer because you are restoring state. Once you do that you lose the HttpOnly cookies hidden inside the CookieContainer. So, a more permanent solution would be using Sockets directly for that request, read the raw request as a string, extract the cookie and set it to the next requests. Here's the code for using Sockets in Windows Phone 8:
public async Task<string> Send(Uri requestUri, string request)
{
var socket = new StreamSocket();
var hostname = new HostName(requestUri.Host);
await socket.ConnectAsync(hostname, requestUri.Port.ToString());
var writer = new DataWriter(socket.OutputStream);
writer.WriteString(request);
await writer.StoreAsync();
var reader = new DataReader(socket.InputStream)
{
InputStreamOptions = InputStreamOptions.Partial
};
var count = await reader.LoadAsync(512);
if (count > 0)
return reader.ReadString(count);
return null;
}
There is also a second possibility - to manually go through response headers, grab and then parse Set-Cookie headers using a bunch of custom code.
It looks something like that, when you are going to match and save a single PHPSESSID cookie (assume LatestResponse is your HttpResponseMessage containing website response):
if (LatestResponse.Headers.ToString().IndexOf("Set-Cookie:") != -1) try
{
string sid = LatestResponse.Headers.ToString();
sid = sid.Substring(sid.IndexOf("Set-Cookie:"), 128);
if (sid.IndexOf("PHPSESSID=") != -1)
{
settings.Values["SessionID"] = SessionID = sid.Substring(sid.IndexOf("PHPSESSID=") + 10, sid.IndexOf(';') - sid.IndexOf("PHPSESSID=") - 10);
handler.CookieContainer.Add(new Uri("http://example.com", UriKind.Absolute), new System.Net.Cookie("PHPSESSID", SessionID));
}
} catch (Exception e) {
// your exception handling
}
Note this code inserts the cookie to CookieContainer for that object's life unless manually deleted. If you want to include it in a new object, just pull the right setting value and add it to your new container.

Auth failure implementing X-FACEBOOK-PLATFORM authentication using Objective-C and C++

I'm implementing the X-FACEBOOK-PLATFORM XMPP authentication in Objective C (but using mostly C++ code) and I am getting always a failure:
<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>
I have the the app registered and the Id and Secret are as follows:
FacebookId #"136973476410894"
FacebookSecret #"f6e269fe158b4a04d00ce8b311453ccd"
I retrieve the session Token with FBConnect asking for the privileges:
#"publish_stream" ,#"xmpp_login" , #"offline_access"
The Session token is called token in the code (see below)
And then the program asks for the authentication mechanism:
<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="X-FACEBOOK-PLATFORM"/>
Receiving the challenge: <challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl">dmVyc2lvbj0xJm1ldGhvZD1hdXRoLnhtcHBfbG9naW4mbm9uY2U9OTAzMTM5MjY2ODk3N0Q0ODMyNDQ2MDY1REMzMTE5RTc=</challenge>
Then the Facebook Auth body extracted from the challenge: version=1&method=auth.xmpp_login&nonce=9031392668977D4832446065DC3119E7.
key: version, value: 1.
key: method, value: auth.xmpp_login.
key: nonce, value: 9031392668977D4832446065DC3119E7.
token: "BAAB8k59ntg4BANNuTHAkjTZBk3pW8pZBD7jWIpZBt8cf65oAT4eDm9euloGCX9NzfF9HwKQxUdEQ15YfeFtkdZAHVpkjL0j4CF0lZCQeuNTBXrvkbtUXC"
APIkey: "136973476410894"
APISecret: "f6e269fe158b4a04d00ce8b311453ccd"
Using the code from below a response is built:
token = Session token from FB connect: (BAAB8k59ntg4BANNuTHAkjTZBk3pW8pZBD7jWIpZBt8cf65oAT4eDm9euloGCX9NzfF9HwKQxUdEQ15YfeFtkdZAHVpkjL0j4CF0lZCQeuNTBXrvkbtUXC)
APIkey = FacebookId (136973476410894);
APISecret = FacebookSecret (f6e269fe158b4a04d00ce8b311453ccd);
string call_id=[[NSString stringWithFormat:#"%0.0f", [[NSDate date] timeIntervalSince1970]] UTF8String];
string signature1 = "api_key=" + APIkey
+ "call_id=" + call_id
+ "method=auth.xmpp_login"
+ "nonce=" + nonce
+ "session_key=" + token
+ "v=1.0"
+ APISecret;
string md = MD5(signature1);
//std::transform(md.begin(), md.end(),md.begin(), ::tolower);
string response2 = "method=auth.xmpp_login&api_key=" + APIkey + "&session_key=" +token + "&call_id=" + call_id + "&sig=" + md + "&v=1.0&" + "nonce=" + nonce;
printf("++base64EncodedResponse response2: %s.\n", response2.c_str());
string response2Base64 = Base64::Encode(response2);
Built response: method=auth.xmpp_login&api_key=136973476410894&session_key=BAAB8k59ntg4BANNuTHAkjTZBk3pW8pZBD7jWIpZBt8cf65oAT4eDm9euloGCX9NzfF9HwKQxUdEQ15YfeFtkdZAHVpkjL0j4CF0lZCQeuNTBXrvkbtUXC&call_id=1321457495&sig=5f376192b2dd1f5f928f651a996ce757&v=1.0&nonce=9031392668977D4832446065DC3119E7
Stanza sent(response): <response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">bWV0aG9kPWF1dGgueG1wcF9sb2dpbiZhcGlfa2V5PTEzNjk3MzQ3NjQxMDg5NCZzZXNzaW9uX2tleT1CQUFCOGs1OW50ZzRCQU5OdVRIQWtqVFpCazNwVzhwWkJEN2pXSXBaQnQ4Y2Y2NW9BVDRlRG05ZXVsb0dDWDlOemZGOUh3S1F4VWRFUTE1WWZlRnRrZFpBSFZwa2pMMGo0Q0YwbFpDUWV1TlRCWHJ2a2J0VVhDJmNhbGxfaWQ9MTMyMTQ1NzQ5NSZzaWc9NWYzNzYxOTJiMmRkMWY1ZjkyOGY2NTFhOTk2Y2U3NTcmdj0xLjAmbm9uY2U9OTAzMTM5MjY2ODk3N0Q0ODMyNDQ2MDY1REMzMTE5RTc=</response>
And the server returns:
<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>
I don't know where the problem is, it looks right to me, but there is no way to authenticate. Does anybody knows if there is any way to debug with the server the reason for the failure? May it be that the App is not yet in the App Store?
If someone can help it would be very welcome!
Since no one responded and someone else can get tricked by this same error due to the fact that this code appears on some examples about Facebook Authentication- I will post the response myself.
Everything is almost ok, it only requires the tag session_key to be changed for access_token in the signature1 string and in the response2 string.

Using Http Post to AddList() in Sharepoint

On a remote client, I'm trying to create a new list in a sharepoint site. Right now, I'm building a CAML string and sending it via http post to my sharepoint site. I've used this method to update list items and create dws folders, but I can't seem to get AddList to work. I get an error "Remove server returned error:NotFound."
here is my CAML:
string soapEnv =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<AddList xmlns=\"http://schemas.microsoft.com/sharepoint/soap\">" +
"<listName>" + listName + "</listName>" +
"<description>" + "A Test list" + "</description>" +
"<templateID>100</templateID>" +
"</AddList>" +
"</soap:Body>" +
"</soap:Envelope>";
return soapEnv;
I send this in an http Post with these settings:
uri = "[my sharepoint site]/_vti_bin/lists.asmx";
WebClient client = new WebClient();
client.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/";
client.Headers["content-type"] = "text/xml; charset=utf-8";
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(uri, UriKind.Absolute), "POST", CAML);
}
catch (Exception ex)
{
MessageBox.Show("Error in upload string async: " + ex.Message);
}
Any ideas? I'm pretty certain it's not an authentication issue since I've used the exact same method in this same program to do the previously mentioned functions. The sharepoint site I'm adding the list to is a test site in which I have full read/write capabilities.
D'oh!
In this part of the soap:Envelope tag: "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance"
I had XMLSchema-instance" instead of XMLSchema\"". I needed that extra parentheses to finish that string...