Solved

Send Login details through HTTPRequest Object

Posted on 2010-09-07
20
1,047 Views
Last Modified: 2013-11-07
Hi,

I have to send Login details using HTTPRequest class and get the validated result.


Please let me know the code examples.

Thanks,
0
Comment
Question by:futurebuilders
  • 11
  • 9
20 Comments
 
LVL 16

Expert Comment

by:kris_per
ID: 33621236
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33621384

If the login is for form based server authentication (like the ones where you log in a web page), then you have to POST the username and password details using HttpWebRequest as shown in the sample code below:
string postDataString = "";

            postDataString += "username" + "=" + UserName;

            postDataString += "&password" + "=" + Password; // here the &username and &password 

// tags should be the same as used in web page form which can be seen using View Source for the 

//html page



            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

            byte[] postDataBytes = asciiEncoding.GetBytes(postDataString);



            Uri uriLoginForm = new Uri("http://www.test.com/login page address here");



            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriLoginForm);

            webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            webRequest.Referer = "http://www.test.com/"; // actual website address here

            webRequest.KeepAlive = true;

            webRequest.Method = "POST";

            webRequest.ContentType = "application/x-www-form-urlencoded";

            webRequest.ContentLength = postDataBytes.Length;            

            webRequest.AllowAutoRedirect = false;

            webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            System.IO.Stream outStream = webRequest.GetRequestStream();

            outStream.Write(postDataBytes, 0, postDataBytes.Length);

            outStream.Close();



            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());

            string respString = streamReader.ReadToEnd();

            streamReader.Close();



            webResponse.Close();

Open in new window

0
 

Author Comment

by:futurebuilders
ID: 33621927
hi kris,

Thanks for your reply.Will this code be used to validate the userid and password. If yes then how should i read that validation code from werresponse?

thanks
0
 

Author Comment

by:futurebuilders
ID: 33622202
In response string I am getting complete HTML code. How to determine whether my user name and password are valid or invalid. Please let me know
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33622356

If authentication has failed, then the html code you recieved will have the error message like 'login failed' somewhere in that html response...this html code is the same page as it would appear in the browser when you enter wrong username/password......to find where the error message is in the html codeL: write the response string to a text file named for e.g. login_response.htm...and then open this htm file in a browser and then in notepad to identify the location of where the error message is in the html...then accordingly you can code in c# to check for that message...(alternatively instead of saving the response to txt file in code, you can set breakpoint just after getting response, then can move the mouse over the response-text variable name which will show the value like toolip and you can copy the value from there and paste into a txt file and then save)

If authentication is successful, then you would get the same html code as it would come in the browser after logging in successfully....this would be typically a default web page for the user (like say after successfull login in gmail, it goes to inbox)

0
 

Author Comment

by:futurebuilders
ID: 33624683
Thnks for your support.

I did the same as you said. But I did nt get any login related information.Can u please check the response code and let me know whether I am in right way or not.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>World of Warcraft Account Login</title>
<meta http-equiv="imagetoolbar" content="false"/>
<link rel="shortcut icon" href="/login/static/_themes/wam/img/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/master.css?v1"/>
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/master-ie6.css?v1" /><![endif]-->
<link rel="stylesheet" type="text/css" href="/login/static/_themes/wam/css/_lang/en-us.css?v1"/>
<script type="text/javascript" src="/login/static/_themes/common.js?v1"></script>
<script type="text/javascript" src="/login/static/_themes/jquery.js?v1"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var processingStr = "Processing";
</script>
</head>
<body class="en-us">
<div class="page loginView">
<div class="">
<form id="loginForm" class="submitForm" name="loginForm" method="post"
action="?app=wam&amp;ref=https%3A%2F%2Fwww.worldofwarcraft.com%2Faccount%2F&amp;cr=true" onsubmit="login.disableButton('submit', this); return true;">
<div class="formRow accountName">
<label class="formLabel" for="accountName" style="margin-bottom:1px">Battle.net E-mail Address</label>
<input value="" id="accountName"
name="accountName" maxlength="320" type="text" tabindex="1" class="text" />
<div class="errorTooltip">
<div class="tooltipBg">
<p>
Account name required.<br />
</p>
<div class="arrow"></div>
</div>
</div>
<script type="text/javascript">
document.getElementById('accountName').focus();
</script>
</div>
<div class="formRow password">
<label class="formLabel" for="password">Password</label>
<input id="password" name="password"
maxlength="16" type="password" tabindex="2" autocomplete="off" class="text" />
</div>
<input type="submit" class="hiddenSubmit" />
<a class="submit" href="javascript:;" onclick="Form.submit(this)" tabindex="3">Log In</a>
<div class="signUp">
<p>Forgot your account <a href="https://us.battle.net/account/support/password-reset.html">password</a>?
</p>
<p>Don't have an account yet? <a href="https://us.battle.net/account/creation/tos.html?ref=https%3A%2F%2Fwww.worldofwarcraft.com%2Faccount%2F">Sign up now</a>!</p>
</div>
<input type="hidden" name="persistLogin" id="persistLogin" value="on" />
</form>
</div>
<div class="selectLocale">
<p>To view this page in another language:</p>
<a href="javascript:selectLanguage('de-de');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'de_DE')">Deutsch</a>
|
<a href="javascript:selectLanguage('en-us');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'en_US')">English (US)</a>
|
<a href="javascript:selectLanguage('en-gb');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'en_GB')">English (EU)</a>
|
<a href="javascript:selectLanguage('es-mx');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'es_MX')">Español (AL)</a>
|
<a href="javascript:selectLanguage('es-es');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'es_ES')">Español (EU)</a>
|
<a href="javascript:selectLanguage('fr-fr');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'fr_FR')">Français</a>
|
<a href="javascript:selectLanguage('ru-ru');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'ru_RU')">¿¿¿¿¿¿¿</a>
|
<a href="javascript:selectLanguage('ko-kr');" onclick="pageTracker._trackEvent('Locale', 'Change Language', 'en_US', 'ko_KR')">¿¿¿</a>
</div>
<div class="legal">
<p>For security reasons, close your web browser when you are done accessing services that require authentication! Secure Blizzard Entertainment web pages that request your account name and password will contain URLs such as worldofwarcraft.com, blizzard.com, and battle.net.</p>
<div class="legalLinks">
<a href="http://us.blizzard.com/en-us/company/about/privacy.html"
onclick="window.open(this.href);return false;">Online Privacy Policy</a> |
<a href="http://us.blizzard.com/en-us/company/about/termsofuse.html"
onclick="window.open(this.href);return false;">Blizzard Terms of Use</a> |
<a href="http://us.blizzard.com/support/index.xml?locale=en_US">Customer Support</a><br />
<a href="http://us.blizzard.com/en-us/company/about/legal-faq.html"
onclick="window.open(this.href);return false;">&copy;2010 Blizzard Entertainment, Inc. All rights reserved.</a>
</div>
<a class="esrb" href="http://us.blizzard.com/en-us/company/about/privacy.html"><!-- --></a>
</div>
</div>
<script type="text/javascript" src="https://ssl.google-analytics.com/ga.js"></script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker('UA-544112-16');
function _gaInit() {
pageTracker._setDomainName(".battle.net");
pageTracker._initData();
pageTracker._trackPageview();
}
function _htmlDomInit(doc) {
_htmlDom = doc;
_gaInit();
}
/* Partial workaround for Firefox bug 230214 */
if(typeof(document.cookie) == 'undefined') {
var obj = document.createElementNS('http://www.w3.org/1999/xhtml', 'object');
obj.setAttribute('style', 'display:none');
obj.width = 0;
obj.height = 0;
obj.type = 'text/html';
obj.data = 'data:text/html;charset=utf-8,%3Cscript%3Eparent._htmlDomInit%28document%29%3C/script%3E';
document.getElementsByTagName('body')[0].appendChild(obj);
document.__defineGetter__('cookie', function() { return _htmlDom.cookie; });
document.__defineSetter__('cookie', function(c) { _htmlDom.cookie = c; });
} else
_gaInit();
} catch(err) {}
</script>
</body>
</html>
0
 
LVL 16

Accepted Solution

by:
kris_per earned 500 total points
ID: 33626889
This html code is the login page. You can save this html content in notepad with .htm extension and open in browser; you can see what it says. Also note it has a text 'Account name required' which means authentication hasn't happened yet.

This html code also contains the source code of the login form (<form id="loginForm"...). The details from this should be used in the code. In this form, user name input textbox is called 'accountName'; so the text 'accountName' should be used in place of 'username'. Password textbox is called 'password'; so no change required in above code.

Below is a class that wraps this code for login and to get any page after login.

Sample usage:

WebPageData page = new WebPageData();

string loginResultString = page.Login("http://www.site.com", "http://www.site.com/login.aspx", "accountName", "john", "password", "pwd111");

Use the correct urls in the params of this method...

public class WebPageData

    {

        private CookieContainer m_cookieContainer;



        public string Login(string startPageUrl,

                                        string loginFormActionUrl,

                                        string usernameTextBoxName,

                                        string username,

                                        string passwordTextBoxName,

                                        string password)

        {

            // first open the login page to initialise cookie container for this site

            // so that other subsequent requests will work properly



            Uri uriLogin = new Uri(startPageUrl);



            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriLogin);

            webRequest.CookieContainer = new CookieContainer();

            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            System.IO.StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());

            string respString = streamReader.ReadToEnd();

            streamReader.Close();



            m_cookieContainer = webRequest.CookieContainer;



            webResponse.Close();



            // Authenticate now using the loginFormActionUrl



            string postDataString = "";

            postDataString += usernameTextBoxName + "=" + username;

            postDataString += "&" + passwordTextBoxName + "=" + password;

            

            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

            byte[] postDataBytes = asciiEncoding.GetBytes(postDataString);



            Uri uriLoginForm = new Uri(loginFormActionUrl);



            webRequest = (HttpWebRequest)WebRequest.Create(uriLoginForm);

            webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            webRequest.Referer = startPageUrl;

            webRequest.KeepAlive = true;

            webRequest.Method = "POST";

            webRequest.ContentType = "application/x-www-form-urlencoded";

            webRequest.ContentLength = postDataBytes.Length;

            webRequest.CookieContainer = m_cookieContainer;

            webRequest.AllowAutoRedirect = false;

            webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            System.IO.Stream outStream = webRequest.GetRequestStream();

            outStream.Write(postDataBytes, 0, postDataBytes.Length);

            outStream.Close();



            webResponse = (HttpWebResponse)webRequest.GetResponse();

            streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());

            string loginNextPageString = streamReader.ReadToEnd();

            streamReader.Close();

            webResponse.Close();



            return loginNextPageString;

        }



        public string GetWebPageContent(string contentPageUrl)

        {

            Uri uriContentPage = new Uri(contentPageUrl);



            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uriContentPage);

            webRequest.CookieContainer = m_cookieContainer;

            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";



            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());

            string contentPageDataString = streamReader.ReadToEnd();

            streamReader.Close();

            webResponse.Close();



            return contentPageDataString;

        }

    }

Open in new window

0
 

Author Comment

by:futurebuilders
ID: 33630798
Hi,

I migrated your code in to vb.net class file as I am using VB.net for development.

1st I called Login method.If I give username and password correct then this method is returning nothing.If I give username or password this method returning the html page content.

So what does it mean? If credentails are correct then It will return nothing ??

Please provide the answer for my question.

Thanks

0
 
LVL 16

Expert Comment

by:kris_per
ID: 33631866

I think there mustbe some html content after successful login. It will be the content of the page you would get in browser if you login in the browser (for example in gmail, after login next page is inbox or some default page).

If you login to worldofwarcraft in browser what is the page you get? Is it a standard html page?
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33632024

OK. I have just tested this with my worldofwarcraft account and I too have got the same empty result...The fix for this is:

Set AllowAutoRedirect to true in the Login method in the above code.

webRequest.AllowAutoRedirect = true;

After this I have got a valid html content which has my Account Summary with all the 'change email address' links etc...

So make this correction and i hope you too would get the result....
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:futurebuilders
ID: 33635085
Thanks...I will try the above code.

Login method will validates the credentials and if the credentials are valid then it will return login page code.

What is the purpose of method "GetWebPageContent"? And where we will use it? Do we need to call after login method? And what purpose we will use thia method?

Please let me know.

0
 
LVL 16

Expert Comment

by:kris_per
ID: 33635225

GetWebPageContent is to get any page other than the one returned by login...i.e. After successful login, a default page (e.g. account summary) is returned. If you want to get page other than this, then GetWebPageContent can be used after login.

0
 

Author Comment

by:futurebuilders
ID: 33635392
So in this case 1st I should use login method to validate the login credentials
next I want to go to password change page.To do that i have to call method GetWebPageContent .Right?
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33635419

Yes.
0
 

Author Comment

by:futurebuilders
ID: 33685948
Hi,

With your help now i am able to validate the credentials and able to change the password.

Now my requiing rement is after validating the credentials i have to open the inner home page of the web site and show to user.

How can DO that.What nethod i have to use?
Thanks
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33686284

Using the GetWebPageContent method, you can get the html data for the inner home page from the website, save it to a local temp file with .htm extension and then open this temp.htm file in web browser using Process.Start() method as shown below:

ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.Arguments = @"C:\temp\temp.htm";
Process.Start(startInfo);

But note that since authentication has done in the .net program, same authenticated state will not be carried to the browser. User can just view the page.
0
 

Author Comment

by:futurebuilders
ID: 33688251
Thanks.

But my requirement is user should be able to carry the authentication details and he can navigate in to the site.

The base idea here is we are storing user credentials in local data base and when ever user enters user id, we are retrieving his password from local DB and using these credentials to login in to the system- so that user no need to remember his password al times.

PLease provide some solution
Thanks
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33695439

Thing is authentication is done in .net code and you want to use the same authentication state in the browser after that.  I am not sure if thats possible as the .net code and browser are different apps. I think this needs more understanding on how the authentication state is stored internally (like cookies or anything more). I will see if I can do some experiments on this and find something; but I am not sure. Better you look for chances with other experts also by posting another question to see if any other expert has already have the knowledge on this.
0
 

Author Comment

by:futurebuilders
ID: 33695765
Hi,

I got some reference site in other post.With this i am able to open the url in windows application.

But still i did not understand how to pass values to it.

I think if u see them u will get some idea

http://msdn.microsoft.com/en-us/library/3s8ys666.aspx
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22944942.html

PLease see above sites and let me know if you get any idea

Thanks in advance
0
 
LVL 16

Expert Comment

by:kris_per
ID: 33696188

OK. Using WebBrowser control is one option that came to my mind. But still i am not positive about that as well. I would suggess you try the following tests. But note that with WebBrowser control user is tied up using only the windows forms and cant use separate browser.

Test #1:

Create a  Form
Add a button named Login at the top
Add another button named 'Goto page'
Add a WebBrowser control below the buttons

In the login button click, Do the login using the code in the solution above.
In the 'goto page' button, open the inner page (for example change password url) in the webbrowser control (using I think Navigate method of webbrowser control)

Now user clicks Login button. login is done.
Then user clicks the goto page button. this will open the page in the wbebrowser; see if authentication is maintained there or not.

Test 2:
Create a form
Add a button 'Goto login page'
Add another button 'Fill username/pwd'
Add webbrowser control below

When user clicks goto login page, open the login page in webbrowser
Then user will click 'Fill username/pwd' button. This will get the username/pwd from another store and should fill the username and pwd in the opened web page. I dont have a tested code for this now. One option is to use WebBrowser.Document property to find out the username/pwd textboxes and set the values in it. I will see if I can try this and find.
Then user will click the login button in the web page and continue browsing inside the webbrowser.

As I mentioned above, user is tied up with using your win forms app for this.

Option 3:

Is requirement like 'autofill and remember password' feature of the browser? Then why can't you try for an option like that within the context of the browser, like IE Extension plugin, like what Google toolbar does OR using Activex control...? I dont know how exactly to make these things work for your requirement...but I am just throwin some thoughts that might click something for you.

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now