in a wpf application I have to call an external rest service which returns a cookie with session id in it. In all subsequent calls I have to send session id in cookie otherwise it does not return any data.
So how can I retrieve the cookie in wpf code behind class?
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
var domain = EndPoint;
HttpResponseMessage response2 = client.PostAsync(domain, new StringContent(parameters)).Result;
Uri uri = new Uri(domain);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
var cookieWithId = responseCookies.Single(o => o.Name == "JESSSIONID");
where EndPoint has http://mydomain.com:38080/workshop/ and parameters has rest/login?username=usr&password=pwd
Here's an example on how to read cookies from response.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
var domain = "http://yourServiceURL.com";
HttpResponseMessage response = client.GetAsync(domain).Result;
Uri uri = new Uri(domain);
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
var cookieWithId = responseCookies.Single(o => o.Name == "SessionId");
Related
I'm getting a cookie and using it, continue to emulate the steps that corresponding browser steps give. Since the auto-redirection is turned off, I have to execute each step individually, fetching the location in the response headers using it in the next. After three such operations, the response's headers contain location field but it's null. Carrying out the corresponding operations using the browser, contains an actual location in every redirection step.
private static Uri ObtainExecutor(Uri referer, Uri uri, Cookie cookie)
{
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(cookie);
HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieJar,
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = referer;
client.DefaultRequestHeaders.Host = uri.Host;
HttpResponseMessage response = client.GetAsync(uri).Result;
HttpResponseHeaders headers = response.Headers;
return new Uri(uri, response.Headers.Location);
}
I have no idea how to troubleshoot it further. I've compared the headers noticing nothing of relevance. I've sharked it with the same result, not being able to grasp the overload of packages coming in. Of course, I've googled it for over a week too.
I'm sure there's a tiny difference in how the call is executed but I lack ability to see it. The sample below connects to the actual server and shows the spot where the redirection location is missing. (My apologies for the large sample - I tried to make it minimal but making sure not to leave out a relevant detail unclear to me.)
class Program
{
static void Main(string[] args)
{
const string url = "https://www.pensionsmyndigheten.se/service/login/login"
+ "?targetPage=https://www.pensionsmyndigheten.se/service/overview/"
+ "&failurePage=https://www.pensionsmyndigheten.se/service/login/error/login-failed"
+ "&cancelPage=https://www.pensionsmyndigheten.se/";
Uri uri = new Uri(url);
Cookie cookie = GenerateCookie(uri);
Uri discovery = DiscoverService(cookie);
Uri execution = ObtainExecutor(uri, discovery, cookie);
Uri conversation = ObtainConversor(uri, execution, cookie);
}
private static Cookie GenerateCookie(Uri uri)
{
CookieContainer cookieJar = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler { CookieContainer = cookieJar };
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync(uri).Result;
HttpContent content = response.Content;
Cookie cookie = cookieJar.GetCookies(uri)
.Cast<Cookie>()
.First(e => e.Name == "pm_retention_urls");
return cookie;
}
private static Uri DiscoverService(Cookie cookie)
{
string url = "https://www.pensionsmyndigheten.se/service/login/discoresponse"
+ "?spId=default"
+ "&entityID=https%3A%2F%2Feid.legitimeringstjanst.se%2Fmobilt-bankid%2F";
Uri uri = new Uri(url);
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(cookie);
HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieJar,
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = uri;
client.DefaultRequestHeaders.Host = uri.Host;
HttpResponseMessage response = client.GetAsync(uri).Result;
HttpResponseHeaders headers = response.Headers;
return headers.Location;
}
private static Uri ObtainExecutor(Uri referer, Uri uri, Cookie cookie)
{
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(cookie);
HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieJar,
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = referer;
client.DefaultRequestHeaders.Host = uri.Host;
HttpResponseMessage response = client.GetAsync(uri).Result;
HttpResponseHeaders headers = response.Headers;
return new Uri(uri, response.Headers.Location);
}
private static Uri ObtainConversor(Uri referer, Uri uri, Cookie cookie)
{
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(cookie);
HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieJar,
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Referrer = referer;
client.DefaultRequestHeaders.Host = uri.Host;
HttpResponseMessage response = client.GetAsync(uri).Result;
HttpResponseHeaders headers = response.Headers;
// Figure out why the returned redirection URL is empty.
Uri redirection = headers.Location;
// It should be containing the following value.
redirection = new Uri(
"https://idpproxy.pensionsmyndigheten.se/idp/Authn/SamlSP?conversation=e1s1");
return redirection;
}
}
I'm write here because I was trying to send a POST request to a server api,
I tried to send also another request(the first one) and from the response it work({"success":"true", "role":"USER"}). But in the sencond request as a response I get: {"timestamp":1524589409895,"status":403,"error":"Forbidden","message":"Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.","path":"/api/v1/rec"}.
So I put all the cookies but one of them "XSRF -TOKEN" cause my program to crashSystem.Net.CookieException: The 'Name'='XSRF -TOKEN' part of the cookie is invalid
so I discovered that this cookie change every time you create a session
so I tried to get the cookies from the response of the first message and added on the header for the second one, and this is the result
I also set the NETFramework at the 4.5 version
I'm leaving a temporary account here for you so you can try this without creating an account only for a test
Request Payload from firefox
static void Main(string[] args)
{
Uri uri = new Uri("https://www.vcast.it/api/v1/rec");
cookieContainer = new CookieContainer();
cookieContainer.Add(uri, new Cookie("CONSENT", "true"));
cookieContainer.Add(uri, new Cookie("_ga", "GA1.2.940742918.1524584758"));
cookieContainer.Add(uri, new Cookie("_gid", "GA1.2.1691132054.1524584758"));
cookieContainer.Add(uri, new Cookie("remember-me", "Z1hvUnJoOHdIM3dCZ2pmYXVKamFRUT09OkpxSXUzRDVRUXd6UG14eGlVUlJMOXc9PQ"));
clienthandler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, CookieContainer = cookieContainer };
client = new HttpClient(clienthandler);
client.DefaultRequestHeaders.Host = "www.vcast.it";
MainAsync();
}
private static CookieContainer cookieContainer;
private static HttpClientHandler clienthandler;
private static HttpClient client;
static async void MainAsync()
{
Uri uri = new Uri("https://www.vcast.it");
var values = new Dictionary<string, string>
{
{ "username", "XXXX" },
{ "password", "XXXX" },
{ "remember-me", "undefined" },
{ "submit", "" }
};
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://www.vcast.it/apiLogin?appId=58aef0c4ea5d52b2c0e4f2ed", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine("New Cookies:");
var responseCookies = cookieContainer.GetCookies(uri).Cast<Cookie>();
foreach (var cook in responseCookies)
{
cookieContainer.Add(uri, cook);
Console.WriteLine(cook.Name + ":" + cook.Value);
}
Console.WriteLine();
clienthandler = new HttpClientHandler { UseCookies = true, CookieContainer = cookieContainer };
client = new HttpClient(clienthandler);
values = JsonConvert.DeserializeObject<Dictionary<string, string>>("{\"name\":\"Titolo registrazione\",\"fromSuggestion\":false,\"manual\":true,\"followSeries\":false,\"resolution\":\"r576\",\"format\":\"MP4\",\"defaultProvider\":\"vcloud\",\"provider\":\"vcloud\",\"channelId\":\"58138235c9e77c00018242ed\",\"startDate\":1524585300000,\"endDate\":1524588900000,\"startHour\":17,\"startMinute\":55,\"endHour\":18,\"endMinute\":55}");
content = new FormUrlEncodedContent(values);
client.DefaultRequestHeaders.Referrer = new Uri("https://www.vcast.it/manualRec/");
response = await client.PostAsync("https://www.vcast.it/api/v1/rec", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
I will gladly accept any kind of comment or answer
I'm new in API's world but I had a question,
I want to get data from Web API but there's two authentication
First with proxy.
Second with API base authentication.
here's my Get Action code:
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;
this code work fine with me but just in pass over proxy username and password!
How can I continue to Get API Data with authentication username and password?
Since you mentioned "Basic Auth" on comments adding the following lines in addition to what you have might help
var byteArray = Encoding.ASCII.GetBytes($"{yourUsername}:{yourPassword}");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Although there are other popular modes of auth such as OAuth, Bearer etc. Change the key on AuthenticationHeaderValue according to the mode of authentication and set the value appropriately
This should work:
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string user = "user", password = "password";
string userAndPasswordToken =
Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password));
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
$"Basic {userAndPasswordToken}");
HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;
I need some help with the new Windows.Web.Http.HttpClient Class. I am writing my first WP8.1 App right now and it drives me crazy. I am logging into a website like this:
var values = new Dictionary<string, string>();
values.Add("login_username", _username);
values.Add("login_password", _password);
values.Add("login_lifetime", "36000");
var parameters = new HttpFormUrlEncodedContent(values);
var response = await Forum.Http.PostAsync(new Uri("http://foo.bar.xyz"), parameters);
var buffer = await response.Content.ReadAsBufferAsync();
byte[] byteArray = buffer.ToArray();
string content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
if (content.Contains("Wrong password/user name"))
{
return false;
}
return true;
And this works pretty fine. My HttpClient is a static field, like this:
public static HttpBaseProtocolFilter Filter = new HttpBaseProtocolFilter();
public static HttpClient Http = new HttpClient(Filter);
The login works just fine, but it doesn't save the cookies the website sends after logging in. How can I save them and can I send them to the website on every GetAsync()?
You can use HttpClientHandler instead of HttpBaseProtocolFilter. If you must use HttpBaseProtocolFilter, then there is a read-only CookieManager property of type HttpCookieManager that could help you.
Here's an example using HttpClientHandler:
public static CookieContainer Cookies = new CookieContainer();
public static HttpClientHandler HttpClientHandler = new HttpClientHandler() { CookieContainer = Cookies };
public static HttpClient Http = new HttpClient(HttpClientHandler);
After your PostAsync() call returns, you can extract the cookies
var uri = new Uri("http://foo.bar.xyz");
var response = await Forum.Http.PostAsync(uri, parameters);
IEnumerable<Cookie> responseCookies = Cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies) {
Console.WriteLine(cookie.Name + ": " + cookie.Value);
}
If you'd like to re-use a cookie from the initial request, you can create your own CookieContainer and copy the cookie from the response cookies. Or - you could also add a hard-coded cookie like this:
Cookies.Add(new HttpCookie("Name", "Value") { Domain="http://foo.bar.xyz" });
I'm trying to login a website for parsing purpose. while program runs it seems to login to web site. I can see that from fiddler. But at the end of the program, even the status code seems tobe 200, ı find myself not logged in.
string loginUri = "https://www.sample.com";
string username = "username";
string password = "password";
CookieContainer cc = new CookieContainer();
var handler = new HttpClientHandler { CookieContainer = cc };
var request = new HttpRequestMessage(HttpMethod.Post, loginUri);
handler.AllowAutoRedirect = true;
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "return_url", "emagaza.php"},
{ "user_login", "sampleuser"},
{ "password", "sapmplepass"},
{ "dispatch[auth.login]", "Giriş yap"}
});
var client = new HttpClient(handler);
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Any attempt to use cookies failed.
I tried this;
httpWebRequest2.CookieContainer = cc;
HttpWebResponse response3 = (HttpWebResponse)httpWebRequest2.GetResponse();
and I tried this;
var handler2 = new HttpClientHandler { CookieContainer = cc };
var request2 = new HttpRequestMessage(HttpMethod.Get, loginUri);
var response2 = await client.SendAsync(request2);