Skip to content

Instantly share code, notes, and snippets.

@ridomin
Created January 22, 2014 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ridomin/8551069 to your computer and use it in GitHub Desktop.
Save ridomin/8551069 to your computer and use it in GitHub Desktop.
FormsAuthenticationAntiForgeryWebClient.vs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace AppDefinitionDynamicParser
{
public class FormsAuthWebClient
{
class WebClientEx : WebClient
{
private Uri _addr = null;
private CookieContainer _cookieContainer = new CookieContainer();
public CookieCollection Cookies
{
get
{
if (_addr == null)
{
return null;
}
return _cookieContainer.GetCookies(_addr);
}
}
public void SetCookie(string name)
{
_cookieContainer.SetCookies(_addr, name);
}
protected override WebRequest GetWebRequest(Uri address)
{
_addr = address;
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = _cookieContainer;
}
return request;
}
}
WebClientEx client = null;
string baseUrl = string.Empty;
public FormsAuthWebClient(string stsUrl)
{
client = new WebClientEx();
baseUrl = stsUrl;
}
public string Authenticate(string userName, string password)
{
string url = baseUrl + "/account/login";
var token = GetToken(url);
byte[] resultBytes = client.UploadValues(url, "POST", new NameValueCollection
{
{"UserName",userName},
{"Password",password},
{"__RequestVerificationToken", token}
});
string result = Encoding.Default.GetString(resultBytes);
result = result.Substring(1, result.Length - 2);
if ((result.Contains(userName)) && (client.Cookies.Count > 0))
{
Trace.WriteLine(client.Cookies[0].Name + " " + client.Cookies[0].Value);
}
else
{
Trace.Write("No cookies found");
}
return result;
}
public string GET(string path)
{
return client.DownloadString(path);
}
public string GetToken(string path)
{
string html = GET(path);
int pos1 = html.IndexOf("__RequestVerificationToken\" type=\"hidden\" value=\"") +49;
int pos2 = html.IndexOf("\" />", pos1);
return html.Substring(pos1, pos2-pos1);
}
public void AddRequestVerificationToken(string url)
{
string result = client.DownloadString(baseUrl + url);
foreach (Cookie c in client.Cookies)
{
Console.WriteLine(c.Name);
}
}
public string POST(string apiContoller, string data)
{
string result = Encoding.Default.GetString(
client.UploadValues(
baseUrl + apiContoller,
"POST",
new NameValueCollection { { "input", data } }
)
);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment