473,503 Members | 10,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Forms Auth and HttpWebRequest credential -- How?

TK
I have a trouble to get web resopnse from an aspx page which is secured by
Forms Authentication with custom user account database.
My client application is a console application but not a browser. I want to
download a file from my webapplication.
I've learned that the NetworkCredential class gives a way to go but no luck.
My code is as following...just dump out the web response for debugging.

// C#
public void Download(string username, string password, string filename)
{
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://myserver/myapp/download.aspx?file=
" + filename);
req.Method = "GET";
req.Credentials = new NetworkCredential(username, password);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();

StreamReader sr = new StreamReader(res.GetResponseStream());
char[] buf = new char[256];
int count;
while((count = sr.Read(buf, 0, 256)) > 0)
{
string s = new string(buf, 0, count);
Console.Write(s);
}
res.Close();
}

It seems the NetworkCredential doesn't work because above code dumps the
html document of the login page.
How can I accomplish this?
Please help!

best regards,
TK

Nov 18 '05 #1
2 6795
Network Credentials are not used with forms authentication. Using forms
authentication with a console app will be fun.

a little background on forms authentication (FA). when a browser hits a FA
site for the first time, the site redirects the browser to the login page.
the url is decorated with the utl of the return page. the user fill in the
login info, and posts to the site. the login page verifies the login data
and if ok, stores a login ticket in the cookie which is sent back to the
browser along with a redirect to the original page.

to get this working in your app do.

1) do get of the requested page. if you are not logged in, the response will
be a redirect header (307 probably).
2) do a get of the response url which should be the login page
3) parse the login page html for the __VIEWSTATE hidden field. you will need
to post this value.
4) post the __VIEWSTATE, and login field values to the login page aspx.
5) if valid, you should get another redirect response with a cookie to use
on future get/puts, and the url of the original page you requested. if the
site is cookieless, you will get a munged url of the orginally requested
page.
6) with the login cookie or munged url, you can now get your original page.
-- bruce (sqlwork.com)
"TK" <tk****@nospam.emotionalbits.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
I have a trouble to get web resopnse from an aspx page which is secured by
Forms Authentication with custom user account database.
My client application is a console application but not a browser. I want to download a file from my webapplication.
I've learned that the NetworkCredential class gives a way to go but no luck. My code is as following...just dump out the web response for debugging.

// C#
public void Download(string username, string password, string filename)
{
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://myserver/myapp/download.aspx?file= " + filename);
req.Method = "GET";
req.Credentials = new NetworkCredential(username, password);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();

StreamReader sr = new StreamReader(res.GetResponseStream());
char[] buf = new char[256];
int count;
while((count = sr.Read(buf, 0, 256)) > 0)
{
string s = new string(buf, 0, count);
Console.Write(s);
}
res.Close();
}

It seems the NetworkCredential doesn't work because above code dumps the
html document of the login page.
How can I accomplish this?
Please help!

best regards,
TK

Nov 18 '05 #2
TK
Thank you for help, bruce.

I've followed the way you mentioned. Now my app works fine in the step 1 to
step 4, but doesn't work as expected in step 5. I also learned that I have a
SessionState/Cookies handling issue in these process. So I added some codes
for this purpose. Now my code looks like this...

static void Download(string username, string password, string filename)
{
CookieContainer Cookies = new CookieContainer();
TargetUrl = new Uri("http://myserver/myapp/download.aspx?file=" +
filename);

HttpWebRequest req =
(HttpWebRequest)WebRequest.Create(TargetUrl.Absolu teUri);
req.Method = "GET";
req.AllowAutoRedirect = false;
req.CookieContainer = Cookies;

HttpWebResponse res = (HttpWebResponse)req.GetResponse();
String s;

if (res.StatusCode == HttpStatusCode.Found)
{
TargetUrl = new Uri(TargetUrl, res.Headers["Location"]);
req = (HttpWebRequest)WebRequest.Create(TargetUrl.Absolu teUri);
req.Method = "GET";
req.AllowAutoRedirect = false;
req.CookieContainer = Cookies;

res = (HttpWebResponse)req.GetResponse();

String ViewState = null;
StreamReader sr2 = new StreamReader(res.GetResponseStream());
Regex reg = new
Regex("name=\"__VIEWSTATE\"\\s*value\\s*=\\s*(?:\" (?<1>[^\"]*)\"|(?<1>\\S+))
",RegexOptions.IgnoreCase|RegexOptions.Compile d);

while ((s = sr2.ReadLine()) != null)
{
Match m = reg.Match(s);
if (m.Success)
{
ViewState = m.Groups[1].ToString();
break;
}
}
res.Close();

s = "TextBox1=" + username + "&TextBox2=" + password + "&__VIEWSTATE=" +
ViewState;
req = (HttpWebRequest)WebRequest.Create(res.ResponseUri. Scheme + "://" +
res.ResponseUri.Host + res.ResponseUri.AbsolutePath);
req.Method = "POST";
req.ContentLength = s.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = Cookies;

StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(s);
sw.Close();

res = (HttpWebResponse)req.GetResponse();
}

StreamReader sr = new StreamReader(res.GetResponseStream());
while((s = sr.ReadLine()) != null)
{
Console.Write(s);
}

res.Close();
}
The HttpWebResponse after POSTing the login page with id/pass/viewstate
doesn't have expected second redirection to the original page. Instead, it
shows another new login page with StatusCode.OK.

Could you give me another hint please?

best regards,
TK

Nov 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1620
by: scott ocamb | last post by:
hello We are using forms authentication in asp.net for our web site. The code we have implemented works on 2 developers machines and not on a single developers machine. We all use source safe...
0
1191
by: Gary Chamberlain | last post by:
I have a C# aspx application. I also have a VB aspx application for forums. I made the forums as sub web of the main one. It is in a folder called /forums. Because it is a VB app it is running...
2
1722
by: Brad | last post by:
Stupid question time: Why does Forms Auth just keep going to the login page when access is denied? A 403 error is never raised..at least in my testing it doesn't. If I have a particular web...
4
5608
by: 23s | last post by:
I had this problem in the past, after a server reformat it went away, and now after another server reformat it's back again - no clue what's doing it. Here's the flow: Website root is public, no...
6
1644
by: Patrick Olurotimi Ige | last post by:
I have a Forms Auth and use a button that allows users to SignOut below but when they sign out and PRESS THE BACK BUTTON they can see the previous page WHY? Sub SignOut(objSender As Object,...
6
1611
by: Jon | last post by:
If a session times out, but the forms auth is still logged in it's possible for users to go to pages on the site that need those session variables. I was under the impression that using forms auth...
1
1147
by: dhnriverside | last post by:
Hi guys My intranet site is using Windows authentication to get users login and details, and using Roles to determine which pages they can visit. However, I want to give them a page so that...
4
1327
by: dhnriverside | last post by:
Hi guys Ok, I have a website which has an "Artists Only" section, for which you have to login for. This section is contained within its own directory on the server "/aonly". I want to make...
6
3189
by: IntraRELY | last post by:
I have an WinForm (VB.NET) that is launched from an ASP.NET page that uses Form Authentication. After the WinForm is lauched it calls a web service. I want to use the credentials stored in the...
3
1398
by: Smokey Grindle | last post by:
I am using forms authentication with a custom user database... I was wondering, when logging in using forms auth, does the HttpContext.Current.User return the forms logged in user or the AD user...
0
7095
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7294
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7361
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7015
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5602
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5026
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4693
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
1
749
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
403
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.