HttpWebRequest not passing Credentials simple form authentication - c#

My code is like this
Doc doc = new Doc();
string url = HttpContext.Current.Request.Url.AbsoluteUri;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// required for HttpWebResponse.Cookies
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential("username", "password");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.Cookies.Count>0) { // includes ASP.NET_SessionId
bool needsCookie2 = false;
StringBuilder builder = new StringBuilder("Cookie: ");
for(int i = 0; i<response.Cookies.Count; ++i) {
Cookie cookie = response.Cookies[i];
if(!needsCookie2 && cookie.Version!=1)
needsCookie2 = true;
if(i>0)
builder.Append("; ");
builder.Append(cookie.ToString());
}
builder.Append(!needsCookie2? "\r\n": "\r\nCookie2: $Version=1\r\n");
doc.HtmlOptions.HttpAdditionalHeaders = builder.ToString();
}
doc.HtmlOptions.NoCookie = true;
doc.HtmlOptions.HostWebBrowser = false;
// cookieless Forms Authentication adds authentication ticket to the URL
int id = doc.AddImageUrl(response.ResponseUri.AbsoluteUri);
doc.Save(HttpContext.Current.Server.MapPath("~/media/pdf/1212.pdf"));
doc.Clear();
I am using simple form authentication in my website and I need to authenticate this webRequest in order to print a pdf through abcPDF, as my login details are stored in cookie i am trying to get it from there and add to my request. I assume the error is in line request.Credentials = new NetworkCredential("username", "password");

You say the website is using forms authentication, but your request is using basic authentication credentials:
request.Credentials = new NetworkCredential("username", "password");
You'll need to either switch the website to basic authentication, or perform a POST request against your login page to get the session cookie/token to use in subsequent requests.

Related

How to navigate to another website, pass login information and complete login form in C# ASP.Net MVC

I'm trying to create a kind of Auto Login feature in an internal ASP.Net MVC C# tool that will allow support users to quickly login to the various system they support.
I've been able to pass all the values needed to complete the login form via Ajax/jQuery to my controller and then to my Class. As seen below I can open the various URL's based on an if else, but not complete the login form.
I've been looking into httpwebrequests but am not sure how I would structure one to use the variables values (below) to complete the various login form field and then click the button.
public AutoLogin(string Environment, string Username, string OrgId, string UserId, string OrgKey)
{
var env = Environment;
var user = Username;
var org = OrgId;
var userid = UserId;
var orgKey = OrgKey;
if (env == "system1")
{
string url = website;
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
req.Method = "POST";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
req.KeepAlive = true;
req.Headers.Add("Keep-Alive: 300");
req.AllowAutoRedirect = false;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = cookieJar;
string username = user;
string pw = "password";
string orgUid = orgKey;
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write("userEmail=" + username + "&userPass=" + pw + "&orgUid=" + orgUid);
sw.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in response.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1255));
string tmp = reader.ReadToEnd();
response.Close();
}
else if (env == "system2")
{
System.Diagnostics.Process.Start(url2);
}
else if (env == "system3")
{
System.Diagnostics.Process.Start(url3);
}
else
{
}
}
Update:
Added the httpwebrequet code I've been working on but when clicking the button front end it doesn't navigate/open the web page..
For internal sites, the easiest way is to use Windows Authentication in your web sites. Just unlock your PC with your password, then go to your internal web sites without login. Windows can do authentication 'under the hood'. Web.config:
<authentication mode="Windows" />

Having trouble adding authentication to WCF service client using C#

I am calling a WCF service using the follwing code:
string certPath = #"C:\certs\mycert.pem";
var uri = new Uri("http://Myserver/TestService.svc/MyMethod/parm1/parm2");
X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("user", "password");
request.PreAuthenticate = true;
request.ClientCertificates.Add(cert);
var response = request.GetResponse();
But getting
HTTP/1.1 400 Bad Request
error and
No Proxy-Authenticate Header is present
Can someone please point me in the right direction?
I suggest you try
string urlAddress = "http://www.google.com";
string userName = "user01";
string password = "puser01";
string proxyServer = "127.0.0.1";
int proxyPort = 8081;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(urlAddress);
if (userName != string.Empty)
{
request.Proxy = new WebProxy(proxyServer, proxyPort)
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(userName, password)
};
string basicAuthBase64 = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password)));
request.Headers.Add("Proxy-Authorization", string.Format("Basic {0}", basicAuthBase64));
}
Reference:Sending Basic authentication over http

Using HttpWebRequest to login to instagram

Hey guys so I'm trying to write a C# Application in which the user can login to their instagram account from a WPF. The problem I'm having is getting the authorization code. When I use this code I keep getting the login page URL, not the successful login page.
Help please!
Any feedback is appreciated! been stuck on this a while
private static AuthInfo GetInstagramAuth(string oAuthUri, string clientId, string redirectUri, InstagramConfig config,
string login, string password)
{
List<Auth.Scope> scopes = new List<Auth.Scope>();
scopes.Add(Auth.Scope.basic);
var link = InstaSharp.Auth.AuthLink(oAuthUri, clientId, redirectUri, scopes);
// Логинимся по указанному узлу
CookieAwareWebClient client = new CookieAwareWebClient();
// Зашли на страницу логина
var result = client.DownloadData(link);
var html = System.Text.Encoding.Default.GetString(result);
// Берем токен
string csr = "";
string pattern = #"csrfmiddlewaretoken""\svalue=""(.+)""";
var r = new System.Text.RegularExpressions.Regex(pattern);
var m = r.Match(html);
csr = m.Groups[1].Value;
// Логинимся
string loginLink = string.Format(
"https://instagram.com/accounts/login/?next=/oauth/authorize/%3Fclient_id%3D{0}%26redirect_uri%3Dhttp%3A//kakveselo.ru%26response_type%3Dcode%26scope%3Dbasic", clientId);
NameValueCollection parameters = new NameValueCollection();
parameters.Add("csrfmiddlewaretoken", csr);
parameters.Add("username", login);
parameters.Add("password", password);
// Нужно добавить секретные кукисы, полученные перед логином
// Нужны заголовки что ли
string agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
client.Headers["Referer"] = loginLink;
client.Headers["Host"] = "instagram.com";
//client.Headers["Connection"] = "Keep-Alive";
client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
//client.Headers["Content-Length"] = "88";
client.Headers["User-Agent"] = agent;
// client.Headers["Accept-Language"] = "ru-RU";
//client.Headers["Accept-Encoding"] = "gzip, deflate";
client.Headers["Accept"] = "text/html, application/xhtml+xml, */*";
client.Headers["Cache-Control"] = "no-cache";
// Запрос
var result2 = client.UploadValues(loginLink, "POST", parameters);
// Постим данные, Получаем code
// New link не на апи, а на instagram
string newPostLink = string.Format(
"https://instagram.com/oauth/authorize/?client_id={0}&redirect_uri=http://kakveselo.ru&response_type=code&scope=basic", clientId);
HttpWebRequest request =
(HttpWebRequest) WebRequest.Create(newPostLink);
request.AllowAutoRedirect = false;
request.CookieContainer = client.Cookies;
request.Referer = newPostLink;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = agent;
string postData = String.Format("csrfmiddlewaretoken={0}&allow=Authorize", csr);
request.ContentLength = postData.Length;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] loginDataBytes = encoding.GetBytes(postData);
request.ContentLength = loginDataBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(loginDataBytes, 0, loginDataBytes.Length);
// send the request
var response = request.GetResponse();
string location = response.Headers["Location"];
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("--Responce from the webrequest--");
Console.ResetColor();
Console.WriteLine(((HttpWebResponse)response).ResponseUri+"\n\n");
// Теперь вытаскиваем код и получаем аутентификацию
pattern = #"kakveselo.ru\?code=(.+)";
r = new System.Text.RegularExpressions.Regex(pattern);
m = r.Match(location);
string code = m.Groups[1].Value;
// Наконец, получаем токен аутентификации
var auth = new InstaSharp.Auth(config); //.OAuth(InstaSharpConfig.config);
// now we have to call back to instagram and include the code they gave us
// along with our client secret
var oauthResponse = auth.RequestToken(code);
return oauthResponse;
}
}
I was using this website as an example and CookieAwareWebClient is just a WebClient that handles Cookies. I'll post it below:
using System;
/// <summary>
/// A Cookie-aware WebClient that will store authentication cookie information and persist it through subsequent requests.
/// </summary>
using System.Net;
public class CookieAwareWebClient : WebClient
{
//Properties to handle implementing a timeout
private int? _timeout = null;
public int? Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
//A CookieContainer class to house the Cookie once it is contained within one of the Requests
public CookieContainer Cookies { get; private set; }
//Constructor
public CookieAwareWebClient()
{
Cookies = new CookieContainer();
}
//Method to handle setting the optional timeout (in milliseconds)
public void SetTimeout(int timeout)
{
_timeout = timeout;
}
//This handles using and storing the Cookie information as well as managing the Request timeout
protected override WebRequest GetWebRequest(Uri address)
{
//Handles the CookieContainer
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = Cookies;
//Sets the Timeout if it exists
if (_timeout.HasValue)
{
request.Timeout = _timeout.Value;
}
return request;
}
}
Are you sure the login process on the website don't use javascript in some step(s)?
As far as i'm aware, if it's the case webrequests won't do the job.
All datas/actions that are javascript related will be non-existent through mere webrequests.
I noticed that for security reasons, Websites with personnal accounts tend to mix their login process with javascript now, to avoid bots requests.
Okay So I Figured out the issue. If you want to use webrequests and webresponses you need to make sure that the header information is correct. The issue with mine was I wasn't passing enough information from the browser. To see this information i used Tamper Data
It's an add on for Firefox and allows you took look at everything you are sending or receiving to/from the server.

ASP.NET and WordPress Single Sign-On

I am trying to get the cookie from the wordpress website programatically and use the asp.net website to store the cookie on the browser.
What i wanted to happen is that, the cookie I got will be stored in the browser so that when I browse that page in the wordpress website, the login page will not be shown.
Is there a problem with the code below?
var url = "https://app.myDomain.com/bfSignin.php";
var cookies = new CookieContainer();
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var data = "passWord=asdf1234&userName=premium";
var buffer = Encoding.ASCII.GetBytes(data);
using (var stream = request.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
}
var response = (HttpWebResponse)request.GetResponse();
response.Cookies.Add(cookies.GetCookies(new Uri(url)));
response.Close();
var cookie = cookies.GetCookies(new Uri(url))[0];
var newCoookie = new HttpCookie(cookie.Name, cookie.Value);
newCoookie.HttpOnly = true;
newCoookie.Path = "/test/";
this.Response.Cookies.Add(newCoookie);
return View();
here is the screenshot if the http response header

How to pass credentials to httpwebrequest for accessing SharePoint Library

I'm trying to read files from a SharePoint document library using HttpWebRequest. In order to do that I have to pass some credentials. I'm using the below request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/msexcel";
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
request.Credentials = new NetworkCredential(UserName, PassWord);
Is this the correct way to pass credentials?
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).
Your code looks fine if you need to run a request from server side code or under a different user.
Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.
If you need to set the credentials on the fly, have a look at this source:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
NetworkCredential cred;
if (username.Contains(#"\")) {
string domain = username.Substring(0, username.IndexOf(#"\"));
username = username.Substring(username.IndexOf(#"\") + 1);
cred = new System.Net.NetworkCredential(username, password, domain);
} else {
cred = new System.Net.NetworkCredential(username, password);
}
CredentialCache cache = new CredentialCache();
if (authtype.Contains(":")) {
authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
}
cache.Add(new Uri(siteurl), authtype, cred);
return cache;
}

Categories

Resources