How can I use auth cookie in cookie Aware Client to access secured web page? - asp.net

Initially I'm login in to a secured webpage,then m getting the cookie manually and then i have to set the cookie while making another call to fetch data from authorized web url.
how can I make one cookie aware client which do not require to set the auth cookie again and again. it should automatically set the auth cookie and get the required data.
My code is
CPSession retVal = null;
if (guid != "")
retVal = TokenManager.getSessionInfo(guid);
ServicePointManager.ServerCertificateValidationCallback = delegate
{ return true; };
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(address);
httpWReq.CookieContainer = new CookieContainer();
Encoding encoding = new UTF8Encoding();
byte[] bdata = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "PUT";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.CookieContainer.SetCookies(new Uri(address), retVal.getAttributeValue(CookieType)); // here I'm setting cookie manually.
httpWReq.ContentLength = bdata.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(bdata, 0, bdata.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());

You can create one cookie aware client like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace SunPowerService.Service
{
public class CookieAwareWebClient : WebClient
{
public CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
}
and you can call it like this
using (var client = new CookieAwareWebClient())
{
Uri uri = new Uri("YourUrlToGetAuthCookie");
client.m_container.SetCookies(uri, strCookieVal);
jsonresponse = client.DownloadString(uri);
}

Related

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

Calling Rest Api with HTTP authentication

I have to call a Rest API securely. I have an authenticate API which returns a token. I need to add this token the API I am calling.
This is the usual way I know of calling the Rest API. I need to append string token to this request.
// *** Establish the request
string token= getAuthenticate(username,password,out token );
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(lcUrl);
// *** Retrieve request info headers
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader loResponseStream = new StreamReader(response.GetResponseStream());
string lcHtml = loResponseStream.ReadToEnd();
response.Close();
loResponseStream.Close();
Not Sure what's the problem... To get the response from the Rest Uri you can do like below :
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(yourUrl + token); // Append Here
request.Method = "GET"; // GET or POST Define Here
//http.Accept = "application/json"; // Add if require
//http.ContentType = "application/json"; // Add if require
String test = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
test = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
Or You can use Simple requests through WebClient:
For Example:
WebClient webClient = new WebClient();
string json = string.Empty;
// Downloads JSon String
json = webClient.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London,uk"); // Replace your URL + Token...
There is third party component also available = RestSharp.
I am using HttpClient, no different at all. I thought this way more clean : http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
var uri = "http://example.com";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token_you_want_to_used);
var response = await httpClient.GetAsync(uri);
string result = await response.Content.ReadAsStringAsync();
}

Web API Login with Cookie

I have an ASP.Net Web API and the documentation states I need to save an Auth Token to a cookie then pass it back for API requests. I can get the Auth Token without a problem. My question is what is the best way to save the cookie and send it back in the request.
I create a cookie in the RequestMessage, but I cannot find a way to send it back when making a request against the API. How do I preserve the state of the Login/cookie.
Any help is greatly appreciated, thanks.
Update
I am now able to obtain the cookie from the response. I am using this tutorial. http://www.asp.net/web-api/overview/working-with-http/http-cookies Let me point out if you want to use this tutorial make sure you update the Web API 4's code base. In the below method i am trying to simply, Login and Logout. However, I am receiving an Error Code 500.
public HttpWebResponse InitializeWebRequest()
{
//HttpResponseMessage logoutMessage = await Logout("bla");
string responseData = string.Empty;
string url = GetServerEndPoint();
string authToken = string.Empty;
string loginInstance = "https://example.com";
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
IList<string> authHeader = responseData.Split('{', '}').ToList();
authToken = authHeader[2].Substring(13, 25);
string sessionId = response.Headers.Get(8);
var nv = new NameValueCollection();
nv["sid"] = sessionId;
nv["token"] = authToken;
CookieHeaderValue cookieVal = new CookieHeaderValue("session", nv);
// Log out
string loginInstance2 = "https://example.com";
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(loginInstance2);
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Headers.Add(nv);
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponseAsync().Result;
}
return response;
}
WOW WHAT A PAIN!
I have no idea why this took me so long to figure out, but after hours and hours and DAYs, of trying to get this stupid auth to work I finally figured it out. Here is the code.
One weird thing is I had to create the header format for the cookie. Which by definition isn't a true cookie, it is a damn header value. I had to create the header title, because when I extracted the JSON object from the file and converted it to string I was unable to keep the format in tact from the file.
public HttpWebResponse InitiliazeWebRequest()
{
string responseData = string.Empty;
string loginInstance = "url + logincreds";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
var toke = response.Headers.Get("authToken");
JObject o = JObject.Parse(responseData);
_authToken = (string)o["response"]["authToken"].ToString();
return response;
}
return response;
}
public HttpWebResponse LogOut()
{
string responseData = string.Empty;
string loginInstance = "https://www.example.com/logout";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Cookie: authToken=" + _authToken);
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
return response;
}
return response;
}

Programatically Login http://waec2013.com/waecexam/ in asp.net

Guys I try to login to http://waec2013.com/waecexam/ website by using
HttpWebRequest
CookieContainer
There is another technique I can use webbrowser but as this is web application so I cannot use webbrowser.
But no luck is this possible that I can login to that website and get the specific data?
I do reverse engineering and do some coding but not achieve my result.
Any Suggestions
string formUrl = "http://waec2013.com/waecexam/";
string formParams = string.Format("adminName={0}&adminPass={1}&act={2}",
"passwaec", "cee660","login");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string getUrl = "http://waec2013.com/waecexam/Leads.php";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Finally I have resolve my own question and post for you guys if you need it.
public class CookiesAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public CookiesAwareWebClient()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
((HttpWebRequest)request).CookieContainer = CookieContainer;
return request;
}
}
using (var client = new CookiesAwareWebClient())
{
var values = new NameValueCollection
{
{ "adminName", "passwaec" },
{ "adminPass", "cee660" },
{ "x", "0" },
{ "y", "0" },
{ "act", "login" },
};
// We authenticate first
client.UploadValues("http://waec2013.com/waecexam/index.php", values);
// Now we can download
client.DownloadFile("http://waec2013.com/waecexam/leadExp.php?act=export",
#"c:\abc.txt");
}
Add this at the start of your method:
var cookies = new CookieContainer();
After each line where you create a webrequest assing the cookies to the instantiated request:
WebRequest req = WebRequest.Create(formUrl);
req.CookieContainer = cookies;
This will store any incoming cookies and send all cookies in the container to the webserver when GETing POSTing.
You don't need to use the Set-Cookie header in that case.

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .
I use this code .
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request =
System.Net.HttpWebRequest.Create("http://spsdev2:1009");
System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();
//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();
I get error in myReq.GetResponse();
Error :The remote server returned an error: (401) Unauthorized.
Edit
This code work for me :)
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I add credentials for HttpWebRequest.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}

Resources