Getting .aspauth cookie through https - asp.net

This worked well on http, but doesn't work on https.
private Cookie GetAuthCookie(string user, string pass)
{
var http = WebRequest.Create(_baseUrl+"Users/Login") as HttpWebRequest;
http.AllowAutoRedirect = false;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
http.CookieContainer = new CookieContainer();
var postData = "UserName=" + user + "&Password=" + pass + "&RememberMe=true&RememberMe=false&ReturnUrl=www.google.com";
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (var postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
var httpResponse = http.GetResponse() as HttpWebResponse;
return httpResponse.Cookies[FormsAuthentication.FormsCookieName];
}

Its probably an SSL cert issue, you'll see this with accessing SSL via WebClient or WebRequest depending on the situation with your certificate issuer. See this prior question for details on how to get around this.

Related

Tableau Unexpired Trusted Ticket - including ClientIP

I have an ASP.NET web application in which I'm rendering different tableau dashboards from a site based on the menu clicked by the user. I have multiple menus and each menu was tied to a tableau URL.
Tableau Trusted Authentication has been implemented to get the trusted ticket from the tableau server. Once the ticket has been retrieved, I am appending the ticket to the dashboard URL along with the server name for each menu.
The trusted ticketing module is working fine and the visualizations are getting rendered in my web application. However, frequently I am getting a message of "Could not locate unexpired ticket" error.
On checking with this error, this is due to the ticket calls getting duplicated.
I reached out to the support regarding this and got a response that I can add client_ip during my trusted ticketing.
Tableau Trusted Ticket
I am not able to find any code article related to adding client_ip in trusted ticketing.
Below is my trusted ticket code.
public class TableauTicket
{
public string getTableauTicket(string tabserver, string sUsername)
{
try
{
ASCIIEncoding enc = new ASCIIEncoding();
string postData = string.Empty;
string resString = string.Empty;
postData = "username=" + sUsername + "";
// FEATURE 816 END - Custom Visualization - KV
if (postData != string.Empty)
{
byte[] data = enc.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
req.ContentLength = data.Length;
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(stream: res.GetResponseStream(), encoding: enc);
resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
else
{
resString = "User not authorised";
return resString;
}
}
catch (Exception ex)
{
string resString = "User not authorised";
return resString;
string strTrailDesc = "Exception in tableau ticket - " + ex.Message;
}
}
public int Double(int i)
{
return i * 2;
}
}
Can anyone please let me know how the client_ip can be passed in trusted ticketing code?
Also, the client IP will get changed for each user and how this will be handled in the trusted ticketing?
UPDATE
I have solved the issue using the source code provided by tableau on how to embed the view in SharePoint.
Below is the code which may help users having the same issue.
string GetTableauTicket(string tabserver, string tabuser, ref string errMsg)
{
ASCIIEncoding enc = new ASCIIEncoding();
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
string postData = "username=" + tabuser + "&client_ip=" + Page.Request.UserHostAddress;
byte[] data = enc.GetBytes(postData);
try
{
string http = _tabssl ? "https://" : "http://";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(http + tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// Write the request
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
// Do the request to get the response
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(res.GetResponseStream(), enc);
string resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
// if anything bad happens, copy the error string out and return a "-1" to indicate failure
catch (Exception ex)
{
errMsg = ex.ToString();
return "-1";
}
}
Assuming your code is working, (I have done this part in Java and not really an expert in asp.net) all you have to do is to add something like:
postData = postData +"&client_ip=" +<variable for client IP>;
The way it is handled on tableau server is :
you turn on wgserver.extended_trusted_ip_checking on Tableau server. see details here
Tableau will match the client IP you passed in the POST request 'client_ip=XXX.XXX.XXX.XXX' while obtaining the token, with the actual IP of the the machine where the browser is trying to access tableau server.

errors running HttpWebRequest.GetResponse - 401 unauthorized

I am using Lymbix client library for sentiment analysis.
When I run the code I am getting an error in (WebResponse)httpRequest.GetResponse(): 401-Unauthorized
(available at https://github.com/lymbix/.NET-Wrapper)
The function containing 401 error is given below:
private static string Post(string url, string data, List<string> headers)
{
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/x-www-form-urlencoded";
if (headers != null)
{
foreach (string header in headers)
{
httpRequest.Headers.Add(header);
}
}
// write request?
byte[] postData = Encoding.UTF8.GetBytes(data.ToString());
httpRequest.ContentLength = postData.Length;
httpRequest.GetRequestStream().Write(postData, 0, postData.Length);
// read response
WebResponse webResponse = (WebResponse)httpRequest.GetResponse();
StreamReader webResponseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
return webResponseStream.ReadToEnd();
}
It's saying you're not authorized, so you need to provide credentials.
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.Credentials = new NetworkCredential("username","password");
httpRequest.UseDefaultCredentials = false; //the default is false, but I included it here just to illustrate that it needs to be false in order to use the specified credentials

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.

Forward a QueryString to another Server

I have a webapp that accepts a messageid and status as a QueryString from an external server. I am migrating the webapp to a new server, but I need the new server to forward the QueryString to the old server in case the old server is still waiting for updates, and until I can get my clients migrated over.
The External website calls my webapp with ?MSGID=12345678&RESPONSE=0
eg:
http://dlrnotify.newserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I need my code behind GetResponse.aspx to process the message locally, and then forward the request to the old server. eg, calling:
http://dlrnotify.oldserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I don't really want to redirect the user to the old web server, just to pass the querystring on from my app.
I can get the QueryString by calling Response.QueryString.ToString() I just need to know how to post that to the old server without upsetting anything.
Sorry if this is a dumb question, I don't work with web apps very often and am obviously using the wrong search terms.
You can use HttpWebRequest and HttpWebResponse for this. Below is an example to use thses
Uri uri = new Uri("http://www.microsoft.com/default.aspx");
if(uri.Scheme = Uri.UriSchemeHttp)
{
HttpWebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
Sample Code on how to Post Data to remote Web Page using HttpWebRequest
Uri uri = new Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312");
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
After executing your code (process message) on the new server, manually generate a HttpWebRequest which should be to your old server with the same querystring as you already figured out to form.
I have a task which is same as your post. But there is a little more in that.
As we have two web applications, one in asp.net and other in PHP. In both we create user profiles. Now the task is to Create users in Asp.NET application and we need to save the same information in PHP application from Asp.Net app.
I am using the below code for that but it is not wroking, Can you please look at it and let me know what I am missing.
CookieContainer cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(#"http://localhost/admin/config/popup_user_info_brand.php");
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.CookieContainer = cookies; // note this
request.Method = "POST";
string boundary = System.Guid.NewGuid().ToString();
string Username = "admin";
string Password = "admin";
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
request.Credentials = new NetworkCredential(Username, Password);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Content-Disposition: form-data; name=\"name\"");
sb.AppendLine("Singh");
sb.AppendLine("Content-Disposition: form-data; name=\"username\"");
sb.AppendLine("Singh123");
sb.AppendLine("Content-Disposition: form-data; name=\"email\"");
sb.AppendLine("a#b.com");
sb.AppendLine("Content-Disposition: form-data; name=\"password\"");
sb.AppendLine("P#ssword");
// This is sent to the Post
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
HttpContext.Current.Response.Write(reader.ReadToEnd());
}
}
}
}
Note:- PHP web site is a 3rd party, we have no access on code.
Thanks,
Ginni.

Resources