Forms Authentication

A typical website that implements forms authentication will contain HTML like this:

<form action="http://www.somesite.com/login" method="post"><input type="text" id="user" name="username"><input type="password" id="pass" name="password"><button type="submit" id="login-btn">Log In</button></form>

Here's how to log into such a site:

 
using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
    static void Main()
    {
        string loginUri = "http://www.somesite.com/login";
        string username = "username";
        string password = "password";
        string reqString = "username=" + username + "&password=" + password;
        byte[] requestData = Encoding.UTF8.GetBytes(reqString);

        CookieContainer cc = new CookieContainer();
        var request = (HttpWebRequest)WebRequest.Create(loginUri);
        request.Proxy = null; request.CookieContainer = cc; 
        request.Method = "POST";

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = requestData.Length;
        using (Stream s = request.GetRequestStream())
            s.Write(requestData, 0, requestData.Length);

        using (var response = (HttpWebResponse)request.GetResponse())
            foreach (Cookie c in response.Cookies) 
               Console.WriteLine(c.Name + " = " + c.Value);
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.